如何从Sql Server表中获取列名和其他信息?

时间:2014-01-31 07:34:27

标签: sql sql-server database sql-server-2008

我需要获取列名以及其他信息,例如

DATA_TYPE, CHARACTER_MAXIMUM_LENGTH ,NUMERIC_PRECISION, NUMERIC_SCALE, IS_NULLABLE, IS_IDENTITY,ORDINAL_POSITION , Primary Key from table

我使用了以下查询

Select  C.COLUMN_NAME as 'ColumnName',
        C.DATA_TYPE as 'Datatype', 
        C.CHARACTER_MAXIMUM_LENGTH as 'MaxLength',
        C.NUMERIC_PRECISION as 'Precision',
        C.NUMERIC_SCALE as 'Scale',
        C.IS_NULLABLE as 'Is_NULL',
        C.IS_IDENTITY,
        C.ORDINAL_POSITION as 'Position',
        isnull(Z.CONSTRAINT_NAME,0) as 'PrimaryKey'
From INFORMATION_SCHEMA.COLUMNS As C 
Outer Apply (
    Select CCU.CONSTRAINT_NAME 
    From INFORMATION_SCHEMA.TABLE_CONSTRAINTS As TC 
    Join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As CCU 
        On CCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
    Where TC.TABLE_SCHEMA = C.TABLE_SCHEMA And 
          TC.TABLE_NAME = C.TABLE_NAME And 
          TC.CONSTRAINT_TYPE = 'PRIMARY KEY' And 
          CCU.COLUMN_NAME = C.COLUMN_NAME ) As Z 
Where C.TABLE_NAME = 'tablename'

问题在于C.IS_IDENTITY,如果我删除它,那么查询工作正常

请建议我如何通过此查询获取身份信息

1 个答案:

答案 0 :(得分:2)

对于IS_IDENTITY,请在选择查询中使用以下表达式

COLUMNPROPERTY(object_id('tablename'), C.COLUMN_NAME, 'IsIdentity')