SQL Magic and tips that are too small to warrant their own pages (read Carl doesn’t know enough about them) but are still pretty sweet and worth noting how to do!
Temporary Tables And Variables
Instantiated in tempdb
- [https://github.com/carlpaton/SQLStatements/blob/master/mssql/General/table%20variables.sql](https://github.com/carlpaton/SQLStatements/blob/master/mssql/General/table variables.sql)
- [https://github.com/carlpaton/SQLStatements/blob/master/mssql/General/temporary%20tables.sql](https://github.com/carlpaton/SQLStatements/blob/master/mssql/General/temporary tables.sql)
- Temporary Tables
You can create local and global temporary tables. Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions.
1 | -- Temporary table |
1 | -- Table Variables |
A Pro Tip!
1 | IF(OBJECT_ID('[tempdb].[dbo].[#settings]') IS NOT NULL) |
DateAdd & Current Date Stamps
1 | --- add using hours |
Order By Random
Select a random record from a large table
1 | SELECT TOP 1 * |
Waitfor Delay
10 seconds
1 | WAITFOR DELAY '00:00:10'; |
Constraints
The constraint will be called CON_some_useful_meaningful_name__my_column
and is for the column my_column
. The CON_
prefix can be denoted as anything useful to your organization, always follow the suggestions of your DBA or the existing naming conventions in the database.
The constraint below means my_column
has to be UNIQUE
.
1 | USE myInstance; |
Print & Convert
When print things out for the user to see your proc doing something you will need to convert types. TIP! Set SET NOCOUNT ON
first so you dont get (n row(s) affected)
in your messages!
1 | DECLARE @Counter int = 0; |
@@ROWCOUNT
Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.
1 | SELECT * FROM dbo.foo WHERE id > 5; |