MSSQL 中如何判断两个表的所有数据是否相同(两个表的字段已经相同)

字段非常多
2025-03-23 06:23:39
推荐回答(2个)
回答1:

这种适合做拼接

 

给你一个我之前自己写过的一个拼接做参考,有点类似

***********用途************
*1、历史表数据还原
*2、字段拼接
*3、实际表中数据插入历史表
*/
declare @sql varchar(max) = '',@zd varchar(max)
--获取最大的ID值
declare @maxid int
select A_id,name into #ls from (select ROW_NUMBER() over(order by c.name) A_id,c.name from 
(select a.name 'A_name',b.* from sysobjects a,syscolumns  b
where a.xtype='u' and a.name = 'a01'
and a.id = b.id) c,
(select a.name 'A_name',b.* from sysobjects a,syscolumns  b
where a.xtype='u' and a.name = 'a01_insert'
and a.id = b.id) d
where c.name = d.name) j
select @maxid = max(j.A_id) from #ls
--循环拼接字段
declare @id int = 1
while(@id <= @maxid)
begin
 select @zd = j.name from #ls j
 where j.a_id = @id
 set @id = @id + 1
 --拼接字段
 set @sql = @sql + @zd + ','
  
end
--拼接sql语句
set @sql = 'insert into a01(' + left(@sql,len(@sql) - 1) + ') ' + 'select ' + left(@sql,len(@sql) - 1) + ' from a01_insert'
--输出sql语句
print @sql
--执行sql语句
--exec(@sql)
go

回答2:

--假设分别是A表和B表,sql 如下:
declare
tableA_count number;
tableB_count number;
C_tableA CURSOR;
begin 

select count(1) into tableA_count from A ;

select count(1) into tableB_count from B ;

C_tableA is selct * from A;

if tableA_count=tableB_count then 
   for C_cursor in C_tableA loop
       select * from A where exists (selcet 1 from B where A.column1=B.column1 and A.column2=B.column2...) and A.column1=C_cursor.column1 and ..;
       if SQL%NOTFOUND
           dbms_output.put_line("2个表的数据不是一样的");
           return;
       else;
    END LOOP;
    dbms_output.put_line("2个表的数据是一样的");     
  
else
       dbms_output.put_line("2个表的数据是一样的");
  
end;

没有测试,不过思路没有问题。