通用SQL Server查詢表結構指令碼

來源:互聯網
上載者:User

 

工作中遇到一個需求,要查詢表結構以及索引、主鍵,本來搞定了,可突然又不好使了,因為我第一次寫的指令碼只能相容SQL Server 2005,用在SQL Server 2000裡面就報錯了,鬱悶,我再改,這次是通用的了,看它還敢給我報錯! --查詢索引和主鍵SELECT
    IndexId     = idx.indid,
    IndexName   = idx.Name,
    ColumnName  = col.Name,
    Sort        = CASE INDEXKEY_PROPERTY(idx.id, idx.indid, idxk.keyno, 'IsDescending')
                  WHEN 1 THEN 'DESC'
                  WHEN 0 THEN 'ASC'
                  ELSE '' END,
    PrimaryKey  = CASE objPK.xtype
                  WHEN 'PK' THEN '√'
                  ELSE ''END
FROM
    sysindexes idx
    INNER JOIN sysobjects c
        ON idx.id=c.id
        AND c.xtype='U'
    LEFT JOIN sysobjects objPK
        ON objPK.[name]=idx.[name]
    LEFT JOIN sysindexkeys idxk
        ON idx.id = idxk.id
        AND idx.indid = idxk.indid
    LEFT JOIN syscolumns col
        ON col.colid = idxk.colid
        AND col.id = idxk.id
WHERE
    c.name='TableName' --這裡改成表名
    AND col.Name IS NOT NULL --查詢表結構SELECT
    ID           = col.colorder, 
    [Name]       = col.name,
    [SystemType] = types.name, 
    [Length]     = CAST(CASE WHEN types.name IN (N'nchar', N'nvarchar') AND col.length <> -1 THEN col.length/2 
                             ELSE col.length END
                        AS int)
FROM
    syscolumns col 
    LEFT JOIN systypes types
        ON col.xtype = types.xusertype 
    INNER JOIN sysobjects obj
        ON col.id     = obj.id
        AND obj.xtype = 'U'
        AND obj.name  <> 'dtproperties' 
WHERE
    obj.name='TableName'--這裡改成表名ORDER BY
    col.colorder 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.