You are on page 1of 2

SQLServer TSQL CheatSheet

DECLARE and SET Varibales Single Line Comments


DECLARE @Mojo int SET @mojo = 1 --THIS IS A COMMENT
SET @Mojo = 1
SELECT @Mojo = Column FROM Table Multi-Line Comments
WHERE id=1 /* This is a comment
IF / ELSE IF / ELSE Statement that can span
IF @Mojo < 1 multiple lines
BEGIN */
PRINT 'Mojo Is less than 1' Try / Catch Statements
END BEGIN TRY
ELSE IF @Mojo = 1 -- try / catch requires
BEGIN SQLServer 2005
PRINT 'Mojo Is 1' -- run your code here
END END TRY
ELSE BEGIN CATCH
BEGIN PRINT 'Error Number: ' +
PRINT 'Mojo greater than 1' str(error_number())
END PRINT 'Line Number: ' +
CASE Statement str(error_line())
SELECT Day = CASE PRINT error_message()
WHEN (DateAdded IS NULL) THEN -- handle error condition
'Unknown' END CATCH
WHEN (DateDiff(day, DateAdded, While Loop
getdate()) = 0) THEN 'Today' DECLARE @i int
WHEN (DateDiff(day, DateAdded, SET @i = 0
getdate()) = 1) THEN 'Yesterday' WHILE (@i < 10)
WHEN (DateDiff(day, DateAdded, BEGIN
getdate()) = -1) THEN 'Tomorrow' SET @i = @i + 1
ELSE DATENAME(dw , DateAdded) PRINT @i
END IF (@i >= 10)
FROM Table BREAK
Add A Column ELSE
ALTER TABLE YourTableName ADD CONTINUE
[ColumnName] [int] NULL; END
Rename a Column CREATE a Table
EXEC sp_rename CREATE TABLE TheNameOfYourTable (
'TableName.OldColName', ID INT NOT NULL IDENTITY(1,1),
'NewColName','COLUMN'; DateAdded DATETIME
Rename a Table DEFAULT(getdate()) NOT NULL,
EXEC sp_rename 'OldTableName', Description VARCHAR(100) NULL,
'NewTableName'; IsGood BIT DEFAULT(0) NOT NULL,
TotalPrice MONEY NOT NULL,
Add a Foreign Key
ALTER TABLE Products WITH CHECK CategoryID int NOT NULL
ADD CONSTRAINT [FK_Prod_Man] REFERENCES Categories(ID),
FOREIGN KEY(ManufacturerID) PRIMARY KEY (ID)
REFERENCES Manufacturers (ID); );
Add a NULL Constraint User Defined Function
ALTER TABLE TableName ALTER COLUMN CREATE FUNCTION dbo.DoStuff(@ID
ColumnName int NOT NULL; int)
RETURNS int
Set Default Value for Column AS
ALTER TABLE TableName ADD BEGIN
CONSTRAINT DECLARE @result int
DF_TableName_ColumnName DEFAULT 0 IF @ID = 0
FOR ColumnName; BEGIN
Create an Index RETURN 0
CREATE INDEX IX_Index_Name ON END
Table(Columns) SELECT @result = COUNT(*)
Check Constraint FROM table WHERE ID = @ID
ALTER TABLE TableName RETURN @result
ADD CONSTRAINT CK_CheckName CHECK END
(ColumnValue > 1) GO
SELECT dbo.DoStuff(0)