How to Declare a variable in SQL Server ?


This content was proof-read by Grammarly. You can Try Grammary for FREE

You will most likely declare a variable in the SQL Server and use it in the SQL Statements. You can use the DECLARE statement and specify the variable and datatype and optionally provide a default value.

For example , You can declare an NewEmployeeJobTitle variable using the DECLARE statement and provide a default value as ‘Chief Executive Officer’

DECLARE @NewEmployeeJobTitle nvarchar(50) = 'Chief Executive Officer';

This variable can later be used within the T-SQL Query.

use AdventureWorks2014
GO
DECLARE @NewEmployeeJobTitle nvarchar(50) = 'Chief Executive Officer';
SELECT * FROM HumanResources.Employee
WHERE JobTitle = @NewEmployeeJobTitle

You can declare a variable without assigning a value for it in which case , the variable value will be NULL.

image
%d bloggers like this: