I'm sure this is easy but I'm still getting syntax errors when I run it in SQL Server Management Studio v17.4.
I have table T1 which has serial numbers, and I just need to iterate through and check how many times they appear in T2. I tried like
declare @serial int
select @serial = select serial from T1
while @serial
begin
select count(*) from T2 where Serial = @serial
end
But I get an error:
Incorrect syntax near the keyword 'select'
How to do it? Thanks.
5条答案
按热度按时间ukxgm1gy1#
Instead of while loop, just join the tables and use an aggregate. Something like:
Without sample data I can't test it out for you, but that will perform a lot better for you.
46qrfjad2#
Simply
There is no need to declare a variable or to use a loop.
If you want to return
0
for serials which not exists in the second table useLEFT JOIN
insteadSimple Demo
sczxawaw3#
First of all, doing:
Doesn't mean that it will start to magically loop for every value of
serial
thatT1
has, it will just assign one value of serial to your variable (if it was correctly written anywayselect @serial = serial from T1
).What you want doesn't really make sense to do it in a loop; sql works in sets, and you should try to write your code accordingly. In this case, a simple
JOIN
should do:t1qtbnec4#
Seems like you could just do this in one quick statement, rather than a loop.
omhiaaxx5#
Yes it is a syntax error
This will select the 1st value from Table T1.
This will remove the error but the query written will not yeald the required output.
You need to loop through table T1 and for each value of T1 search in T2.
See if the below simple query helps