User Tools

Site Tools


sql_cheat_sheet

This is an old revision of the document!


SQL Cheat Sheet

CREATE

CREATE TABLE
	Table1 (
		  Id       INT      NOT NULL
		, SomeDate datetime NULL
		CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ( Id ASC )
	)

INSERT

-- Combining an INSERT with a SELECT.
INSERT
	Table1 (
		  Col1
		, Col2
		, Col3
	)
SELECT
	  Table2.Col1
	, Table2.Col2
	, Table2.Col3
FROM
	Table2

UPDATE

-- Combining an UPDATE with a SELECT.
UPDATE
	Table1
SET
	  Table1.Col1 = Table2.Col1
	, Table1.Col2 = Table2.Col2
FROM
	Table1
INNER JOIN
	Table2
ON
	Table2.Id = Table1.Id

Randomness

SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS RandomNumber
 
SELECT LEFT(CAST(NEWID() AS VARCHAR(100)), 6) AS RandomString

Fix Logins After DB Restore

-- Replace username with the actual username.
EXEC sp_change_users_login 'report'
EXEC sp_change_users_login 'auto_fix', username
EXEC sp_change_users_login 'update_one', username, username
sql_cheat_sheet.1334810983.txt.gz · Last modified: 2017/01/01 19:52 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki