如何在变量中检查并存储两个表是否具有相同的内容?
我有像
这样的数据的表变量declare @table1 table (id int)
insert into @table1 (id) values (1), (2), (3)
并且作为第二个表我有查询
select T.id from SomeTable T
inner join @table1 T1 on T.id = T1.id
查询返回数据:
id
-----
1
2
在这种情况下,我需要将false(0)写入declare @HasAccess BIT
变量。
当查询返回数据时:
id
-----
1
2
3
然后我需要将{1}写入@HasAccess
答案 0 :(得分:1)
嗯。有各种各样的方式。
鉴于您有一列,您可以这样做:
select (case when count(*) = 0 then 1 else 0 end)
from t1 full join
t2
on t1.id = t2.id
where t1.id is null or t2.id is null;
检查两个表中的id
是否匹配。
另一种方式使用union all
:
select (case when count(*) = 0 then 1 else 0 end)
from (select id, sum(in_t1) as num_t1, sum(in_t2) as num_t2)
from ((select id, 1 as in_t1, 0 as in_t2 from table1) union all
(select id, 0, 1 from table2)
) tt
group by id
) tt
where num_t1 <> 1 or num_t2 <> 1;
答案 1 :(得分:1)
另一种选择(只是为了好玩)。这将比较整个表字段和值。
我怀疑不是LARGE表的最佳选择
示例强>
Select IsIdentical = case when (Select * from Table1 Order by id For XML Raw)
= (Select * from Table2 Order by id For XML Raw)
then 1 else 0 end
编辑 - 内部加入选项
Select IsIdentical = case when (Select * from @Table1 Order by id For XML Raw)
= (Select A.*
From SomeTable A
Join @Table1 B on A.ID=B.ID
Order By id For XML Raw)
then 1 else 0 end
答案 2 :(得分:0)
使用EXCEPT
:
SET @HasAccess = ISNULL(
( SELECT 0
WHERE EXISTS(
SELECT ID /* add more columns here if needed */
FROM @table1
EXCEPT
SELECT ID /* add more columns here if needed */
FROM SomeTable )), 1 )
ID
中的所有@table1
,SomeTable
NULL
除外
ISNULL
,因此{{1}} 可以轻松扩展到多个列的比较。