63

I am trying to make a simple query to my server and want the result to be stored in the variable @times.

DECLARE @times int

SET @times = SELECT COUNT(DidWin)as "I Win"
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

IntelliSense says Wrong syntax near Select

jao
  • 17,666
  • 15
  • 61
  • 95
Lumpi
  • 2,553
  • 5
  • 35
  • 46

5 Answers5

118

You just need parentheses around your select:

SET @times = (SELECT COUNT(DidWin) FROM ...)

Or you can do it like this:

SELECT @times = COUNT(DidWin) FROM ...
Mike Valenty
  • 8,765
  • 2
  • 28
  • 32
11

You can select directly into the variable rather than using set:

DECLARE @times int

SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

If you need to set multiple variables you can do it from the same select (example a bit contrived):

DECLARE @wins int, @losses int

SELECT @wins = SUM(DidWin), @losses = SUM(DidLose)
FROM thetable
WHERE Playername='Me'

If you are partial to using set, you can use parentheses:

DECLARE @wins int, @losses int

SET (@wins, @losses) = (SELECT SUM(DidWin), SUM(DidLose)
FROM thetable
WHERE Playername='Me');
lambacck
  • 9,532
  • 3
  • 33
  • 46
  • You can but you don't **need** to select directly into the variable. – ypercubeᵀᴹ May 22 '11 at 14:23
  • 1
    @ypercube: But if you get in the habit of using select, you wont try to use 2 or more set + select commands when 1 select can set all the variables at once. I also find the SELECT to be more readable. – lambacck May 22 '11 at 14:25
  • I disagree on the readability but that's personal taste. Readable for me would be `SET (@var1, @var2, ..., @varn) = (SELECT ... )` – ypercubeᵀᴹ May 22 '11 at 14:28
  • I like that the assignment is close the the variable name. If you have *many* assignments, it could be harder to pick out which item in the select applies to which variable. Not to mention that you end up having more code. – lambacck May 22 '11 at 14:32
2

You want:

DECLARE @times int

SELECT @times =  COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

You also don't need the 'as' clause.

James Wiseman
  • 29,282
  • 17
  • 92
  • 156
0

You can use SELECT as lambacck said or add parentheses:

SET @times = (SELECT COUNT(DidWin)as "I Win"
FROM thetable
WHERE DidWin = 1 AND Playername='Me');
a1ex07
  • 36,234
  • 12
  • 86
  • 101
-1

If you need to print the result with column name "c", or read the result in your code by using "c" column name:

DECLARE @c int;
SELECT c = count(*) from '%Table%' WHERE '%condition%'
Vasil Valchev
  • 5,439
  • 2
  • 33
  • 39
  • 1
    This will not assign the result to the variable. It will instead return a result set with a column named c. The variable @c would be null. And you can't assign and return in a single statement. – Wes H Apr 19 '21 at 15:04