How to use Assignment Operator in SQL Server - SQL Server / TSQL Tutorial Part 128

The equal ( = ) sign is used in TSQL as assignment operator. You will be using assignment operator many time when you write your TSQL Code.

1) Assign Value to Variable
Assignment Operator can be used to set the value for variable. You can simply assign static value to variable by using Assignment Operator or value returned by query.

Declare @i int
SET @i=2000
Print @i

Declare @Cnt int
SET @Cnt=(Select COUNT(*) from dbo.Customer)
Print @Cnt

Declare @CntRow int
Select @CntRow=Count(*) from dbo.Customer
Print @CntRow

2) Let's say you have dbo.Customer table and you want to add a static value column, You can use Assignment Operator to assign value to newly added column. In below example I am adding Region column by assigning 'North America'.

--Create Customer Table
Create table dbo.Customer
 (Id int,
  FName VARCHAR(50),
  LName VARCHAR(50),
  CountryShortName CHAR(2),
  Age tinyint)
--Insert Rows in dbo.Customer Table
insert into dbo.Customer
Values (

Also we can use the assignment operator for Alias. I have used CustomerID alias for ID column by using assignment operator.

Age,Region='North America' 
From dbo.Customer

What is Assignment Operator in SQL Server and How to use Assignment Operator - SQL Server / TSQL Tutorial

1 comment: