sqlserver 比較兩個表的列


一、問題 
給了兩個各有四五十個列的表,找出他們相同的列和不同的列

二、查詢兩個表的列,存在臨時表

--#a ,#b都是臨時表,當前連接斷開后自動刪除
--RANK() OVER (ORDER BY syscolumns.name DESC) AS 是SQL2005支持的,在每行記錄前加上自增序號
--IDENTITY(INT,1,1) 函數必須要和into聯合使用

1、將表的列存入#a--'destTbl'比較的表名

select *  into #a from (select  RANK() OVER (ORDER BY syscolumns.name DESC) AS 序號,syscolumns.name
  from syscolumns,sysobjects
    where syscolumns.[id]=sysobjects.[id] 
          and sysobjects.[name]='destTbl') as t    

select * from #a

1 姓名
2 課程
3 id
4 cno

2、將表的列存入#b--'student'比較的表名

select  序號= IDENTITY(INT,1,1),syscolumns.name
    into #b  from syscolumns,sysobjects
    where syscolumns.[id]=sysobjects.[id] 
          and sysobjects.[name]='student'


select * from #b

1 id
2 name
3 cno

三、分析比較各個表列的異同

用下列語句,或者稍作改動比較
select * from #b where name in (select name from #a) 
select * from #a where name not in (select name from #b) 
select * from #a a, #b b where a.name=b.name 
select * from #a a left join #b b on a.name=b.name


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM