Friday, November 14, 2008

Convert INT to Comma-Separated NVARCHAR

A quick expression to change an INT like 1234567 to a comma-separated NVARCHAR like '1,234,567'.

REPLACE(CONVERT(NVARCHAR, CONVERT(MONEY, CountPages), 1), '.00', '')

Thursday, November 13, 2008

Rebuild All Indexes on All Tables

Here's a small script to rebuild all the indexes on all the tables in a given database:

EXEC sp_MsForEachTable 'USE [YourDatabase]  PRINT ''?''  DBCC DBREINDEX (''?'', '' '', 70)'

Be sure to read Books OnLine about "DBCC DBREINDEX" - it's probably not something you want to do during peak hours.

Get Row Counts for all Tables

Here's a quick way to get the row counts for every table in a given database:

DBCC UPDATEUSAGE(YourDatabase)

SELECT so.name AS 'Table Name',
       si.rows AS 'Row Count'
  FROM sysobjects so
  JOIN sysindexes si
    ON so.id   = si.id
 WHERE so.type = 'U'
   AND si.indid IN (0, 1)
 ORDER BY si.rows DESC

This is quick because it looks in the system tables instead of at the tables themselves. (If you include the DBCC UPDATEUSAGE statement, it will take a while, but is sure to be accurate.)

Tuesday, November 4, 2008

Jeff's SQL Server Blog

It just doesn't get any better than this:

Jeff's SQL Server Blog: "The Joy of Blog Feedback"