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 will use the last value. (Normal order rules apply - if no sort is given, the order is not guaranteed.)
CREATE TABLE #Test (Example INT)
INSERT INTO #Test VALUES (1), (2)
DECLARE @Variable INT
SELECT @Variable = Example
FROM #Test
ORDER BY Example ASC
PRINT @Variable
2
SELECT TOP 1 @Variable = Example
FROM #Test
ORDER BY Example ASC
PRINT @Variable
1
If there are no rows returned by the query, the variable's value won't change:
SELECT TOP 0 @Variable = Example
FROM #Test
ORDER BY Example ASC
PRINT @Variable
1