0

I was in a database class the other night and we noticed that the following code seemed to work, but we could not logically understand why.

DECLARE @counter  integer
SET @counter = 42
WHILE @counter < 52
BEGIN 
    set @counter = @counter+++++ + 1
    PRINT 'The counter is ' + cast(@counter as char) 
END

We realized that we could add any number of +'s on to our @counter variable, and SSMS does not seem to care, even though it does not match the original variable. Anybody happen to know why this works?

Pang
  • 9,564
  • 146
  • 81
  • 122
Risquey
  • 16
  • 1
  • Interesting. If you change it to `+-1` it goes into an infinite loop. If you change it to `+-+-+1` it also works. – Nick.Mc Feb 18 '16 at 01:42
  • You might find [this](https://technet.microsoft.com/en-us/library/ms174362(v=sql.110).aspx) helpful. Basically, I'm guessing that only the first "+" is evaluated and all other "+"s are treated as "this is a positive number." So ++1 is the same as +Positive1 – Kidiskidvogingogin Feb 18 '16 at 01:52

1 Answers1

0

Appending a + to a variable name does not change the variable name, as white space is ignored (and + is not a valid character in a variable name anyway).

See here for a discussion about why multiple + signs works. Essentially, every + (or -) after the first one is considered a unary operator.

Community
  • 1
  • 1
Jerrad
  • 5,240
  • 1
  • 18
  • 23