Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Scripting schema updates in MSSQL #1

This SQL statement will alter a table only if a column in the table to be altered does NOT contain a column named 'FavoriteColorId'.

From: http://haacked.com/

IF NOT EXISTS
(
    SELECT * FROM [information_schema].[columns]
    WHERE    table_name   = 'Customer'
    AND      table_schema = 'dbo'
    AND      column_name  = 'FavoriteColorId'
)
BEGIN
    ALTER TABLE [dbo].[Customer]
    ADD FavoriteColorId int

Retrieve MSSQL table information

Retrieve tons of information (length, data type, name, etc.) of columns for a table. Works in (T|MS)SQL (all I've tested it in).

SELECT * FROM information_schema.columns WHERE table_name = 'Customers'

Replace text in a TEXT type data column

// Replace text in a TEXT type data column

SELECT     REPLACE(SUBSTRING(Note, 1, DATALENGTH(Note)), CHAR(13), '<BR>') AS Expr1
FROM         OLD_NOTES

Simple COALESCE example

// Simple COALESCE example

--If all arguments are NULL, COALESCE returns NULL.
COALESCE(expression1,...n) 
--is equivalent to this CASE function:
CASE
WHEN (expression1 IS NOT NULL) THEN expression1
--...
WHEN (expressionN IS NOT NULL) THEN expressionN
ELSE NULL

Simple TSQL cursor

// Simple TSQL cursor
	declare @email nvarchar(255)
	declare CustList cursor for
		SELECT email from STE_EMAILS
	OPEN CustList
	FETCH NEXT FROM CustList 
	INTO @email
	WHILE @@FETCH_STATUS = 0
	BEGIN
	  if (SELECT count(custid) from customer where (current_customer=1) and (notes1 is not null) and (notes1 like '%' + @email + '%')) > 0
		SELECT custid from customer where (current_customer=1) and (notes1 is not null) and (notes1 like '%' + @email + '%')
		print '%' + @email + '%'
	  FETCH NEXT FROM CustList INTO @email
	END
	CLOSE CustList
	DEALLOCATE CustList

find duplicates

SELECT column,COUNT(*) c FROM table
GROUP BY column HAVING COUNT(*) > 1

results show the column value and the number of duplicates for that value

Dynamic ordering without dynamic sql

DECLARE @order int
SET @order = 1
SELECT * FROM users
ORDER BY 
	CASE WHEN @order = 1 THEN [name] END DESC,
	CASE WHEN @order = 2 THEN [name] END ASC,
	CASE WHEN @order = 3 THEN [email] END DESC,
	CASE WHEN @order = 4 THEN [email] END ASC

set the @order to 1-4 to get specific order by clause, setting it to anything else give results as if no order by clause supplied

remember dynamic SQL (creating SQL in a string and then executing) can not be effectively cached so this is a much better option

Randomly ordered results in TSQL

SELECT TOP 10 userID
FROM user
ORDER BY NEWID()

or
SELECT TOP 10
	NEWID() [egg],
	userID
FROM user
ORDER BY [egg]

or
SELECT TOP 10
	NEWID(),
	userID
FROM user
ORDER BY 1

only tried the above with TSQL