[How To] select and assign to a variable in MSSQL

In MSSQL, you can use the SELECT statement to retrieve data from one or more tables, and assign the result to a variable.

The syntax for assigning the result of a SELECT statement to a variable is as follows:

DECLARE @variable_name datatype

SELECT @variable_name = expression
FROM table_name
WHERE some_column = some_value

[adinserter block=”6″]

For example, to assign the value of the “first_name” column of the “employees” table to a variable called @name, you would use the following statement:

DECLARE @name varchar(50)

SELECT @name = first_name
FROM employees
WHERE employee_id = 123

You can also use the SELECT statement to assign the result of a query to a variable.

DECLARE @employee_count INT

SELECT @employee_count = COUNT(*) FROM employees

You can then use the variable later in your query or stored procedure.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.