SQL Server比較2table字段的差異
由於項目前後用了2個數據庫,需要統計數據庫結構的變化,需要統計每個表的變化,由於人工核對挺浪費時間,就寫了一點代碼:
1.統計表的字段數量(查詢表有多少列):
select count(name) from syscolumns where id=object_id(‘表名‘)
eg:select count(name) from syscolumns where id=object_id(‘t_dk‘)
2.查詢數據庫字段名 (表有哪些字段)
select name
from 數據庫名.dbo.syscolumns
where id=(
select id from 數據庫名.dbo.sysobjects
)
eg:
select name
from Catsic_Compare0803DiLong_2017080311.dbo.syscolumns
where id=(
select id from Catsic_Compare0803DiLong_2017080311.dbo.sysobjects where name=‘t_cbjzc‘
)
3.比較兩個數據庫相應表的差異(查詢表對應的字段是否一致)
本部分是基於2寫的:
select * from (
select name
from 數據庫A.dbo.syscolumns
where id=(
select id from 數據庫A.dbo.sysobjects
where name=‘表名A‘)
) T1 FULL OUTER JOIN(
select name from 數據庫B.dbo.syscolumns
where id=(
select id from 數據庫B.dbo.sysobjects
where name=‘表B‘
)
) T2 on T1.name=T2.name
eg:
select * from (
select name
from Catsic_Compare0803DiLong_2017080311.dbo.syscolumns
where id=(
select id from Catsic_Compare0803DiLong_2017080311.dbo.sysobjects
where name=‘t_cbjzc‘)
) T1 FULL OUTER JOIN(
select name from Catsicgl_43_2016Eroad_2017111110.dbo.syscolumns
where id=(
select id from Catsicgl_43_2016Eroad_2017111110.dbo.sysobjects
where name=‘t_cbjzc‘
)
) T2 on T1.name=T2.name
只顯示字段字段名有差異的字段,增加一個條件即可where T1.name is null or T2.name is null
即全部code:
select * from (
select name
from Catsic_Compare0803DiLong_2017080311.dbo.syscolumns
where id=(
select id from Catsic_Compare0803DiLong_2017080311.dbo.sysobjects
where name=‘t_cbjzc‘)
) T1 FULL OUTER JOIN(
select name from Catsicgl_43_2016Eroad_2017111110.dbo.syscolumns
where id=(
select id from Catsicgl_43_2016Eroad_2017111110.dbo.sysobjects
where name=‘t_cbjzc‘
)
) T2 on T1.name=T2.name
where T1.name is null or T2.name is null
SQL Server初學者,鼓勵轉載,共同學習
SQL Server比較2table字段的差異