sql語句查兩個表的列是否一致


一、首先要了解Sqlserver 中系統表對象及表結構查詢的函數:sysobjects、syscolumns以及函數object_id

     

 1. sysobjects ——  系統對象表。 保存當前數據庫的對象,如約束、默認值、日志、規則、存儲過程等

注:重要字段需要解釋的是 xtype,他的數據字段內容分別表示為:

C = CHECK 約束

D = 默認值或 DEFAULT 約束

F = FOREIGN KEY 約束

FN = 標量函數

IF = 內嵌表函數

K = PRIMARY KEY 或 UNIQUE 約束

L = 日志

P = 存儲過程

R = 規則

RF = 復制篩選存儲過程

S = 系統表

TF = 表函數

TR = 觸發器

U = 用戶表

V = 視圖

X = 擴展存儲過程

 

2. sysolumns —— 當前數據庫的所有表里面創建的字段都保留在里面

注:SQL中的sysobjects 的id與syscolumns 的id 存在主鍵關系,即 syscolumns 中的id字段是 sysobjects 表的主鍵對應值(查詢時: select name from syscolumns where id=(select id from sysobjects where name='表名')

 

3. object_id('表名') —— 函數表示直接取表對象的ID值。此方法返回數據庫對象標識號

注:查詢時:  select name from syscolumns where  id =object_id('TB')  等同於上述查詢

 

二、比較同一數據庫中兩個表的對應字段的差異(當兩個表結構一樣時,查詢表對應的字段是否一致)

select * from (
select name
from syscolumns
where id=(
select id from sysobjects
where name='表名1')
) T1
FULL OUTER JOIN(
select name from syscolumns
where id=(
select id from sysobjects
where name='表名2')
) T2 on T1.name=T2.name
where T1.name is null or T2.name is null

 

三、比較在不同數據庫中兩個表的對應字段的差異(當兩個表結構一樣時,查詢表對應的字段是否一致)

select * from (
select name
from gxjmxy.dbo.syscolumns
where id=(
select id from gxjmxy.dbo.sysobjects
where name='TB1')
) T1 FULL OUTER JOIN(
select name from Test.dbo.syscolumns
where id=(
select id from Test.dbo.sysobjects
where name='TB'
)
) T2 on T1.name=T2.name
where T1.name is null or T2.name is null

 

 


免責聲明!

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



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