This is a list of SQL snippets that I find useful.
This page will continue to be a work in project where I plan to add more content as I find it.
I will attempt to add links to the snippets if I pulled them directly from somewhere else or to provide more information.
Create Table
The code below can be used to create a table.
CREATE Table database_name.schema_name.table_name (
primary_column data_type PRIMARY KEY,
column_1 data_type NOT NULL,
column_2 data_type,
...,
table_constraints
);
Insert Into Table
INSERT INTO database_name.schema_name.table_name
VALUES (column_1_value, column_2_value, ...),
(column_1_value, column_2_value, ...),
...;
If the version of SQL server is older or doesn’t accept multiple VALUES sets at one time, you can do an insert with a join for each row.
INSERT INTO database_name.schema_name.table_name
SELECT column_1_value, column_2_value, ...
UNION
SELECT column_1_value, column_2_value, ...
...;
Drop Table
DROP TABLE IF EXISTS database_name.schema_name.table_name;
If the version of SQL Server is older than 2016 or otherwise doesn’t accept the IF EXISTS option, then you can use the following slightly more verbose option.
IF OBJECT_ID('database_name.schema_name.table_name', 'U') IS NOT NULL DROP TABLE database_name.schema_name.table_name;
If the table you are trying to drop is a temporary table, use the following.
IF OBJECT_ID('tempdb.dbo.#table_name', 'U') IS NOT NULL DROP TABLE #table_name;
Leave a Reply