[英]Compare each row values in second table in SQL Server?
I have a scenario where I have to search value of column 1 in first table to see whether it matches some value in another table. 我有一种情况,我必须在第一个表中搜索列1的值,以查看它是否与另一个表中的某些值匹配。
This should continue in a loop until the last row on first table has been compared. 这应该继续循环直到比较了第一个表的最后一行。
No loops needed. 无需循环。 You can do this easily as a set based operation using exists()
您可以使用exists()
作为基于集合的操作轻松完成此操作
select *
from FirstTable
where exists (
select 1
from SecondTable
where FirstTable.Column1 = SecondTable.Column1
);
To find the opposite, where the row in the first table does not have a match based on Column1, you can use not exists()
要找到相反的情况,即第一个表中的行不基于Column1进行匹配,则可以使用not exists()
select *
from FirstTable
where not exists (
select 1
from SecondTable
where FirstTable.Column1 = SecondTable.Column1
);
If you want to identify which rows have a match and don't you can use: 如果要确定哪些行匹配,则可以使用:
select FirstTable.*
, MatchFound = case when x.Column1 is null then 'No' else 'Yes' end
, x.Column1
from FirstTable
outer apply (
select top 1
*
from SecondTable
where FirstTable.Column1 = SecondTable.Column1
) as x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.