Jeremy Coenen

5Jun/090

Get word count from SQL Server table

For one of my projects I needed to go into the database and get a rough estimate of the number of words that needed to be translated from various tables in our database.

I looked around to see if anyone had come up with some t-sql to do this, but did not find much in my initial search so I ended up creating this rudimentary stored procedure.

  1.  
  2. CREATE PROCEDURE GetWordCount (
  3. @tableName NVARCHAR(256),
  4. @columnName NVARCHAR(256)
  5. )
  6. AS
  7. DECLARE @SQL NVARCHAR (4000)
  8.  
  9. SELECT @SQL = 'SELECT SUM( (1 + DATALENGTH(' +@columnName +') -
  10. DATALENGTH(REPLACE(CAST('+ @columnName + '
  11. AS NVARCHAR(MAX)), '' '', '''')))) AS WordCount
  12. FROM ' + @tablename
  13.  
  14. EXEC SP_EXECUTESQL @SQL
  15.  

I'm sure there are flaws in the design (basically counting spaces), but it gets me a close enough estimate.

Note: I ended up using DataLength() over LEN() to be able to hand text/ntext fields and also casted the column as NVARCHAR(MAX) for the very same reason.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.