2

I would like to know if it's possible to create a Count variable like you would in C#.

DECLARE @Count Int
SET @Count = 0

--something happens
SET @Count += 1

--something happens
SET @Count += 1

IF @Count < 3
BEGIN
--Do something
END
1
  • Yes, using the traditional x = x + 1 syntax. What's the purpose? Commented Oct 29, 2015 at 14:07

3 Answers 3

8

In SQL-Server you can do It in following:

SET @count = @count + 1
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, was surprised when nothing on sql counter searches showed me this. But thanks, back to basics :)
sure have to wait 7 min still.
4

In SQL Server 2008+ your code is perfectly valid:

DECLARE @Count INT;
SET @Count = 0;

PRINT @Count;
SET @Count += 1;

PRINT @Count;
SET @Count += 1;

IF @Count < 3
BEGIN
  PRINT @Count;
END

LiveDemo

With version before 2008 you can use full syntax:

SET @Count = @Count + 1;

+= operator

Adds two numbers and sets a value to the result of the operation. For example, if a variable @x equals 35, then @x += 2 takes the original value of @x, add 2 and sets @x to that new value (37).

1 Comment

+= works from SQL-Server2008 on, i'm on 2005 and didn't know it.
0

Yes, it's possibile:

DECLARE @Count AS INTEGER
SET @Count = 0

SET @Count = @Count + 1
SET @Count = @Count + 1
SET @Count = @Count + 1

PRINT @Count --3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.