Select all empty tables in SQL Server

On SQL Server 2005 and up, you can use something like this: ;WITH TableRows AS ( SELECT SUM(row_count) AS [RowCount], OBJECT_NAME(OBJECT_ID) AS TableName FROM sys.dm_db_partition_stats WHERE index_id = 0 OR index_id = 1 GROUP BY OBJECT_ID ) SELECT * FROM TableRows WHERE [RowCount] = 0 The inner select in the CTE (Common Table Expression) calculates … Read more

TSQL – Is it possible to define the sort order?

It’s incredibly clunky, but you can use a CASE statement for ordering: SELECT * FROM Blah ORDER BY CASE MyColumn WHEN ‘orange’ THEN 1 WHEN ‘apple’ THEN 2 WHEN ‘strawberry’ THEN 3 END Alternately, you can create a secondary table which contains the sort field and a sort order. TargetValue SortOrder orange 1 apple 2 … Read more

How to format a numeric column as phone number in SQL

This should do it: UPDATE TheTable SET PhoneNumber = SUBSTRING(PhoneNumber, 1, 3) + ‘-‘ + SUBSTRING(PhoneNumber, 4, 3) + ‘-‘ + SUBSTRING(PhoneNumber, 7, 4) Incorporated Kane’s suggestion, you can compute the phone number’s formatting at runtime. One possible approach would be to use scalar functions for this purpose (works in SQL Server): CREATE FUNCTION FormatPhoneNumber(@phoneNumber … Read more

ANSI_NULLS and QUOTED_IDENTIFIER killed things. What are they for?

OK, from an application developer’s point of view, here’s what these settings do: QUOTED_IDENTIFIER This setting controls how quotation marks “..” are interpreted by the SQL compiler. When QUOTED_IDENTIFIER is ON then quotes are treated like brackets ([…]) and can be used to quote SQL object names like table names, column names, etc. When it … Read more