如何在一行中获取具有列名的表结构?

时间:2014-02-07 11:45:26

标签: sql sql-server

任何人都可以帮我查询单行获取表名,列名,列数据类型,isprimary等。

例如: 我的带有列E_Id,E_Name,E_City的employee表的输出应该如下所示


TabName ColumnName数据类型isprimary Columnname数据类型isprimary Columnname数据类型

员工 - E_Id - int - S - E_Name - varchar - N - E_City - varchar


2 个答案:

答案 0 :(得分:0)

您可以通过以下方式获取表架构

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TABLENAME';
GO

(但输出格式不是你想要的)

来源:http://technet.microsoft.com/en-us/library/ms186778.aspx

答案 1 :(得分:0)

您可以使用INFORMATION_SCHEMA系统视图获取任何表的此信息。 以下是一个例子:

SELECT 
    c.TABLE_NAME, 
    c.COLUMN_NAME, 
    c.DATA_TYPE, 
    CASE WHEN tc.CONSTRAINT_NAME IS NOT NULL THEN 1 ELSE 0 END AS IsPrimary
FROM INFORMATION_SCHEMA.COLUMNS c 
    LEFT JOIN (
        INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu 
        JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
        ON tc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME 
              AND tc.CONSTRAINT_SCHEMA = ccu.CONSTRAINT_SCHEMA 
              AND tc.CONSTRAINT_CATALOG = ccu.CONSTRAINT_CATALOG
          AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
    )
    ON ccu.COLUMN_NAME = c.COLUMN_NAME 
      AND ccu.TABLE_NAME = c.TABLE_NAME 
      AND ccu.TABLE_SCHEMA = c.TABLE_SCHEMA 
      AND ccu.TABLE_CATALOG = c.TABLE_CATALOG
WHERE c.TABLE_NAME = 'Employee'