Assignment operator is used to assign value to any field or variable in sql server.
Syntax of = ( Assignment ) Operator :
SET Variable Name = expression
Variable name can be any valid variable created in sql server. Assignment operator sets value to variable returned by expression.
SELECT FieldName = expression
Field name can be any name. Assignment operator sets value to variable returned by expression.
Examples of = ( Assignment ) Operator :
Example 1 : Assigning string value to field databasename.
SELECT DatabaseName = 'SQL Server'
Output
DatabaseName
SQL Server
Above example how can we assign any value to field.
Example 2 : Assigning field value of table to different Column heading name.
SELECT ID = ProductID, Product = ProductName
FROM Products
Output
ID Product
1 Chai
2 Chang
3 Aniseed Syrup
4 Chef Anton's Cajun Seasoning
5 Chef Anton's Gumbo Mix
Above example illustrates use of assignment operator to assign field value to different column heading name.
Example 3 : Assigning field value to variable.
DECLARE @ProductPrice INT
SELECT @ProductPrice = UnitPrice
FROM Products
WHERE ProductID = 10
PRINT @ProductPrice
Output
31
Above example explains use of assignment operator to assign value of particular field value to sql variable.
Example 4 : Assigning integer value to variable.
DECLARE @NumberOfBooks INT
SET @NumberOfBooks = 10
PRINT @NumberOfBooks
Output
10
Above example explains use of assignment operator to assign integer value 10 to variable @NumberOfBooks in sql server.