General SQL Server Query table structure script

Source: Internet
Author: User
Tags sql server query

 

I encountered a requirement in my work. I had to query the table structure, index, and primary key, but it was suddenly difficult because the script I wrote for the first time was only compatible with SQL Server 2005, in SQL Server 2000, an error is reported. If it is depressing, I will modify it again. This time it is common. I dare to report an error to you! -- Query indexes and primary keys Select
Indexid = idx. indid,
Indexname = idx. Name,
Columnname = col. Name,
Sort = case indexkey_property (idx. ID, idx. indid, idxk. keyno, 'isdesending ')
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' -- change the table name here.
And col. Name is not null   -- Query the table structure 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 policypes 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' -- change the table name here. Order
Col. colorder

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.