如何在SQL Server查询中显示表结构?


72
SELECT DateTime, Skill, Name, TimeZone, ID, User, Employee, Leader 
FROM t_Agent_Skill_Group_Half_Hour AS t

我需要在查询中查看表结构。


3
表结构是什么意思?IMO,您的问题不清楚。
SonerGönül13年

3
我的意思是,例如,列名称技能....查询必须返回技能.. DBINT:int
巴萨姆·加里布

3
我们称其为“表模式”。
纳姆福德2015年

2
SQL Server是我所见过的最糟糕的事情
Akshay Hazari,

Answers:


135

对于SQL Server,如果使用较新版本,则可以使用

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'

有多种获取架构的方法。使用ADO.NET,可以使用架构方法。使用DbConnectionGetSchema方法DataReaderGetSchemaTable方法

假设您有该查询的阅读器,则可以执行以下操作:

using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
    var schema = reader.GetSchemaTable();
    foreach(DataRow row in schema.Rows)
    {
        Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
    }
}

有关更多详细信息,请参见本文


我需要一个查询在Microsoft SQL Management Studio中进行测试:s
Bassam Qarib

1
@BassamQarib-如果需要在Management Studio中进行标记,为什么还要标记问题C#?
PHeiberg

抱歉,我是新用户:ssss
Bassam Qarib

1
我还添加了一个SQL Server查询
PHeiberg 2013年

要访问在特定数据库中定义的表,您可能需要在开始时使用“使用<数据库名称>”,尤其是在不指定连接数据库的情况下执行时。
Yu Shen

45

sp_help tablename 在SQL Server中

desc tablename 在甲骨文


因此,“ sp_help tablename”和“''select * from INFORMATION_SCHEMA.COLUMNS到底有什么区别,其中TABLE_NAME ='tableName''''
Archan Joshi

@ArchanJoshi:试试看,一个又一个地执行,您将看到。“sp_help将”让你在PK的,约束的信息,而其他提供列本身的详细信息
的Damián巴勃罗·冈萨雷斯

在另一种模式则sp_help“schema.tablename”如sp_help将“geo.test”语法表
JohnC

15

试试这个查询:

DECLARE @table_name SYSNAME
SELECT @table_name = 'dbo.test_table'

DECLARE 
      @object_name SYSNAME
    , @object_id INT

SELECT 
      @object_name = '[' + s.name + '].[' + o.name + ']'
    , @object_id = o.[object_id]
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE s.name + '.' + o.name = @table_name
    AND o.[type] = 'U'
    AND o.is_ms_shipped = 0

DECLARE @SQL NVARCHAR(MAX) = ''

;WITH index_column AS 
(
    SELECT 
          ic.[object_id]
        , ic.index_id
        , ic.is_descending_key
        , ic.is_included_column
        , c.name
    FROM sys.index_columns ic WITH (NOWAIT)
    JOIN sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id
    WHERE ic.[object_id] = @object_id
)
SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
    SELECT CHAR(9) + ', [' + c.name + '] ' + 
        CASE WHEN c.is_computed = 1
            THEN 'AS ' + cc.[definition] 
            ELSE UPPER(tp.name) + 
                CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('nvarchar', 'nchar', 'ntext')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') 
                       THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
                     WHEN tp.name = 'decimal' 
                       THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
                    ELSE ''
                END +
                CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END +
                CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
                CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + 
                CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END 
        END + CHAR(13)
    FROM sys.columns c WITH (NOWAIT)
    JOIN sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
    LEFT JOIN sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id
    LEFT JOIN sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id
    LEFT JOIN sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
    WHERE c.[object_id] = @object_id
    ORDER BY c.column_id
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ')
    + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + 
                    (SELECT STUFF((
                         SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END
                         FROM sys.index_columns ic WITH (NOWAIT)
                         JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
                         WHERE ic.is_included_column = 0
                             AND ic.[object_id] = k.parent_object_id 
                             AND ic.index_id = k.unique_index_id     
                         FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ''))
            + ')' + CHAR(13)
            FROM sys.key_constraints k WITH (NOWAIT)
            WHERE k.parent_object_id = @object_id 
                AND k.[type] = 'PK'), '') + ')'  + CHAR(13)

PRINT @SQL

输出:

CREATE TABLE [dbo].[test_table]
(
      [WorkOutID] BIGINT NOT NULL IDENTITY(1,1)
    , [DateOut] DATETIME NOT NULL
    , [EmployeeID] INT NOT NULL
    , [IsMainWorkPlace] BIT NOT NULL DEFAULT((1))
    , [WorkPlaceUID] UNIQUEIDENTIFIER NULL
    , [WorkShiftCD] NVARCHAR(10) COLLATE Cyrillic_General_CI_AS NULL
    , [CategoryID] INT NULL
    , CONSTRAINT [PK_WorkOut] PRIMARY KEY ([WorkOutID] ASC)
)

另请阅读:

http://www.c-sharpcorner.com/UploadFile/67b45a/how-to-generate-a-create-table-script-for-an-existing-table/


2
在SSMS右键单击表中,选择脚本表为>创建到>新建查询编辑器窗口
卢比奥

为什么使这样一项简单的任务变得如此复杂?
弗拉基米尔·努尔

没为我工作。我没有Sql Server Management Studio。我所拥有的只是Azure Sql查询编辑器。
user1229458

14

在SQL Server 2012上,可以使用以下存储过程:

sp_columns '<table name>'

例如,给定一个名为用户的数据库表:

sp_columns 'users'

3

对于最新版本的SQL Server Management Studio在查询编辑器中编写,然后执行“ Alt” +“ F1”



1

我正在尝试使用“ DESC table_name”,但这在psql中对我有用:

select * 
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='table_name'; 

0

要打印模式,我使用jade并导出到数据库文件,然后将其转换为word以进行格式化和打印


1
请考虑解释您的答案。
jpp

0

在SQL Server中,可以使用以下查询:

USE Database_name

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='Table_Name';

而且不要忘了更换Database_name,并Table_name与您的数据库和表名的确切名称。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.