SQL Server比較2table欄位的差異

來源:互聯網
上載者:User

標籤: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欄位的差異

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.