70

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

5 Answers 5

134

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 ...
Sign up to request clarification or add additional context in comments.

Comments

13

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');

4 Comments

You can but you don't need to select directly into the variable.
@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.
I disagree on the readability but that's personal taste. Readable for me would be SET (@var1, @var2, ..., @varn) = (SELECT ... )
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.
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.

Comments

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');

Comments

-2

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%'

1 Comment

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.

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.