Declaring Variables in SQL – Declaration will take place during PARSING, not at Runtime

All SQL variable declarations will take place during parsing but not during Runtime. Let us try simple test to prove it!
Let us try to declare a variable in a loop which runs for 5 times… There are no errors in the execution

DECLARE @i int = 1
while (@i < 5)
begin
	declare @j int = @i
	SET @i = @i + 1
end
select @i, @j

Let us try to declare same variable 2 times one in If and one in Else loop. This will throw error while parsing the query

DECLARE @i int = 1
IF (@i < 5)
	declare @j int = @i
ELSE
	declare @j int = @i + 2
select @i, @j
Advertisements
This entry was posted in knowledge, SQL, SQL Query and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s