MS SQL - SQL cheatsheet

By xngo on August 2, 2019

-- Use 'return' to stop and exit the script.
    RETURN
 
-- Create a temporary table: view.
    CREATE VIEW myView AS
        SELECT * FROM myTable
 
-- True or false Boolean
--    There is no true or false Boolean in MS SQL server. There are only 1 or 0.
 

Format

-- Add thousand separator. 
    SELECT FORMAT(12345, 'N0');        -- Output: 12,345
    SELECT FORMAT(12345.678, 'N2');    -- Output: 12,345.68

String

-- Why prefix N with string, e.g. N'abc'
    --    Because the data type is NVarchar and it is used for Unicode.
    --    N'abc' simply converts your string to Unicode.
 
-- Concatenate string.
    SELECT CONCAT('OpenWritings', '.net')    -- Output: OpenWritings.net
    SELECT CONCAT(ColumnName, '-Xuan')        -- Output: Suffix '-Xuan' to the value of ColumnName
 
-- Single quotes are escaped by doubling them up.
    SELECT 'Escape single quote('')'
 
-- Search 'in ' and replace it with 'out '.
    SELECT REPLACE('in string', 'in ', 'out '); -- Output: out string   

Insert

-- Get the ID after insert statement.
    INSERT INTO Person (name) VALUES('Joe');
    SELECT SCOPE_IDENTITY();

Update

-- Update.
    UPDATE tablename SET col1=value1, col2=value2 WHERE conditions

Date & Time

-- Current date & time.
    SELECT CURRENT_TIMESTAMP  -- 2019-09-07 10:00:39.150
    SELECT GETDATE()            -- 2019-09-07 10:00:39.150
 
-- Add /subtract time
    SELECT DATEADD(day, 1, GETDATE())   -- Add 1 day: 2019-09-08 10:00:39.150
    SELECT DATEADD(hour, -1, GETDATE()) -- Subtract 1 hour: 2019-09-07 09:00:39.150

Declare & set variable

-- Declare & set variables.
    DECLARE @product_id INT, @product_name VARCHAR(255), @product VARCHAR(255)
    SET @product_id = 1234
    SET @product_name = 'fruit'
    SET @product = @product_name + '(' + CAST(@product_id AS VARCHAR) + ')'
 
-- Output: 1234   fruit   fruit(1234)
    SELECT @product_id, @product_name, @product

Loop

-- While loop
    DECLARE @i INT = 0;
 
    WHILE @i < 5
    BEGIN
        SELECT @i;   
        SET @i = @i + 1;
    END;

Systems

-- List all tables in database.
    SELECT * FROM SYSOBJECTS WHERE xtype = 'U';
 
-- Show information about table.
    sp_help TABLENAME;
 
-- Show all database names
    SELECT name, database_id, create_date
        FROM sys.databases
 
-- Show none-system database names
    SELECT name FROM sys.databases 
        WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');

Sample database

Script to create a sample database can be found at MS SQL - Sample database.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.