Tutorial by Examples

DECLARE @Employees TABLE ( EmployeeID INT NOT NULL PRIMARY KEY, FirstName NVARCHAR(50) NOT NULL, LastName NVARCHAR(50) NOT NULL, ManagerID INT NULL ) When you create a normal table, you use CREATE TABLE Name (Columns) syntax. When creating a table variable, you use DECLARE @...
DECLARE @VariableName INT SET @VariableName = 1 PRINT @VariableName 1 Using SET, you can only update one variable at a time.
Using SELECT, you can update multiple variables at once. DECLARE @Variable1 INT, @Variable2 VARCHAR(10) SELECT @Variable1 = 1, @Variable2 = 'Hello' PRINT @Variable1 PRINT @Variable2 1 Hello When using SELECT to update a variable from a table column, if there are multiple values, it wi...
DECLARE @Var1 INT = 5, @Var2 NVARCHAR(50) = N'Hello World', @Var3 DATETIME = GETDATE()
SQL Server 2008 R2 Supported compound operators: += Add and assign -= Subtract and assign *= Multiply and assign /= Divide and assign %= Modulo and assign &= Bitwise AND and assign ^= Bitwise XOR and assign |= Bitwise OR and assign Example usage: DECLARE @test INT = 42; SET @test...
Depending on the structure of your data, you can create variables that update dynamically. DECLARE @CurrentID int = (SELECT TOP 1 ID FROM Table ORDER BY CreateDate desc) DECLARE @Year int = 2014 DECLARE @CurrentID int = (SELECT ID FROM Table WHERE Year = @Year) In most cases, you will want...

Page 1 of 1