原理:数据库A,数据库B
1:得到两个数据库中的用户表
SELECT [name] FROM A.dbo.sysobjects WHERE type='U'
SELECT [name] FROM B.dbo.sysobjects WHERE type='U'
2:定义游标:得到,它们不同的表
3:得到相同表,字段相差个数:
select @A_count=count(*) from dbo.syscolumns where id=object_id(@A_Tb_Name)
select @B_count=count(*) from dbo.syscolumns where id=object_id(@B_Tb_Name)
4:把,数据记录,显示
代码如下:
DECLARE @A_Tb_Name varchar(40) --定义游标操作
DECLARE @B_Tb_Name varchar(40) --定义游标操作
declare @New_Tables varchar(500)
set @New_Tables='要创建的新表:'
declare @is_exist int
declare @sl int
set @sl=0
DECLARE A_cursor CURSOR FOR
SELECT [name] FROM A.dbo.sysobjects
WHERE type='U'
DECLARE B_cursor CURSOR FOR
SELECT [name] FROM B.dbo.sysobjects
WHERE type='U'
-- 打开游标
OPEN B_cursor
-- 提取记录数据
FETCH Next FROM B_cursor Into @B_Tb_Name
WHILE (@@fetch_status = 0 )
BEGIN
set @is_exist=0
open A_cursor
FETCH Next FROM A_cursor Into @A_Tb_Name
WHILE @@fetch_status = 0
BEGIN
if(@B_Tb_Name=@A_Tb_Name)
BEGIN
set @is_exist=1
DECLARE @A_count int
DECLARE @B_count int
use A
select @A_count=count(*) from dbo.syscolumns
where id=object_id(@A_Tb_Name)
use B
select @B_count=count(*) from dbo.syscolumns
where id=object_id(@B_Tb_Name)
if(@B_count-@A_count<>0)
begin
set @sl=@sl+1
declare @temp varchar(50)
set @temp=cast(@sl as varchar)+'
'+@A_Tb_Name
PRINT @temp+space(40-len(@temp))+cast
((@B_count-@A_count) as varchar)
end
END
FETCH Next FROM A_cursor Into @A_Tb_Name
END
CLOSE A_cursor
if @is_exist=0
begin
set @New_Tables=@New_Tables+char(13)+' ['+@B_Tb_Name+']
'
end
FETCH Next FROM B_cursor Into @B_Tb_Name
END
print @New_Tables
CLOSE B_cursor -- 关闭游标
-- 释放游标资源
DEALLOCATE B_cursor
DEALLOCATE A_cursor