Make it possible to declare variables that are only visible within a block - by Erland Sommarskog

Status : 

  Won't Fix<br /><br />
		Due to several factors the product team decided to focus its efforts on other items.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 537275 Comments
Status Closed Workarounds
Type Suggestion Repros 0
Opened 2/27/2010 1:09:50 PM
Access Restriction Public


In modern programming languages, it is usually possible to say things like:

      DECLARE @x int
      SELECT @x = 14

And if you now add:

   SELECT @x

after END, you get a compilation error, as @x is only visible within the block where it was declared.

Not so in T-SQL, where the above is perfectly legal. That is, you can refer to the variable outside the block where it was declared.

There are two advantages with the more modern approach.

1) If you declare a variable to be used only in a block controlled by an IF statement, and then you mistakenly refer to it outside the IF block, you get a compilation error.

2) It is common in a WHILE loop to have one or more work variables. In order to be sure that values from the previous iteration do not linger, you need to explicitly initiate the variables in the beginning of the loop, and if you have lots of variables, you can easily miss one, leading to hard-to-find errors.
Sign in to post a comment.
Posted by Microsoft on 3/18/2011 at 1:33 PM
Hello Erland,

Thank you for submitting this suggestion, but we're trying to clean house and remove items we feel we will likely not address given their priority relative to other items in our queue. We believe it is unlikely that we will address this suggestion, and so we are closing it as “won’t fix”.

This cleaning will help us focus on the high-priority items that we feel need to get done, and we hope that it help provide better clarity to you about the issues we will (and won't) address.

Umachandar, SQL Programmability Team
Posted by Microsoft on 3/3/2010 at 10:46 AM
Hi Erland,
Thanks for your feedback. We are aware of this request and will consider it for a future version of SQL Server.

Umachandar, SQL Programmability Team
Posted by Hugo Kornelis on 2/28/2010 at 1:36 PM
Frankly, I see very liittle benefit from this change, and I'd rather see the development team invest its time anywhere else.
Posted by Jamie Thomson on 2/27/2010 at 10:48 PM
Erland's point #2 makes this worth considering IMO
Posted by Luís Patrício on 2/27/2010 at 2:17 PM
I would suggest that it would be possible to use DECLARE SCOPED, so that we could still declare the variables for further use in code (assuming that the variable occupies memory just after we declare it)