標籤:column 顯示 人工 objects 基於 serve cat com 統計
由於項目前後用了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 where name=‘表名‘
)
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欄位的差異