How to Get a value to a Variable in SQL Server ?

When you use the declare a variable using the DECLARE statement. The same variable can be used to store a value retrieved from the database and later can be used in your SQL Query.

How to Get a value to a Variable in SQL Server ?

For example , you want to retreive the value of the column JobTitle and store it in the variable “NewEmployeeJobTitle”.

use AdventureWorks2014
GO
DECLARE @NewEmployeeJobTitle nvarchar(50)
SELECT @NewEmployeeJobTitle = JobTitle FROM HumanResources.Employee where BusinessEntityID = 5

SELECT @NewEmployeeJobTitle as JobTitle
How to Get a value to a Variable in SQL Server ?

Also , ensure that at most one row is retrieved from the Query by using the PrimaryKey or the Unique Key in the WHERE clause.