I am trying to compute the number of distinct pairs sender_id
, send_to_id
and assign it to a variable @UniqueRequests
. When I try the statmement below, I get an error saying the syntax near )
is incorrect.
DECLARE @UniqueRequests int;
SET @UniqueRequests = (SELECT COUNT(*) FROM (SELECT DISTINCT sender_id, send_to_id FROM friend_request));
So my questions would be
- What is the correct statement?
- It seems that we must use parentheses around a
SELECT
when assigninig a variable. That is to say, we need to writeSET @MyVariable = (SELECT some_expression);
Why is that so? - Is there any documentation page on the use of parentheses in SQL Server in general?
Thank you for your help!
Best Answer
Actually this error is a bit confusing and that's the reason you are asking these questions.
Correct statement would be:
I did testing on some other table with same concept and you may see the result as below:
Answer to these questions are as below:
This is because you are setting the value, and you can't assign keyword and other strings to an int, rather you want to assign the value which means query has to run first and that result you want to assign to this particular integer variable.
Alternatively if you wish to only set the value, you can use below:
You may refer this from Micrososoft, this thread and this link.
Hope this helps.