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

I need to view the table structure in a query.

5
  • 3
    What do you mean as a table structure? Your question isn't clear IMO. Aug 18, 2013 at 11:12
  • 3
    i mean as example the column name skill .... the query must return skill .. DBINT:int Aug 18, 2013 at 11:26
  • 3
    We call that "table schema".
    – namford
    Jun 12, 2017 at 13:49
  • 3
    SQL Server is the worst thing I have seen May 29, 2019 at 6:59
  • The terminal output is horrendous! this is something mysql team got right. Microsoft suck at command line interfaces.
    – hookenz
    Apr 15, 2021 at 2:21

9 Answers 9

182

For SQL Server, if using a newer version, you can use

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

There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection's GetSchema method or the DataReader'sGetSchemaTable method.

Provided that you have a reader for the for the query, you can do something like this:

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

See this article for further details.

3
  • i need a query to test in Microsoft SQL Management Studio :s Aug 18, 2013 at 11:56
  • 1
    @BassamQarib - why do you tag the question C# if you need to do it in Management Studio?
    – PHeiberg
    Aug 18, 2013 at 12:22
  • To access a table defined in a particular database, you may need to have "use <database name>" at the beginning, especially, when you execute without specifying the connected database.
    – Yu Shen
    Feb 27, 2018 at 20:22
64

sp_help tablename in sql server

desc tablename in oracle

3
  • So, what exactly is the difference between "sp_help tablename" and ''' select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='tableName' ''' Mar 10, 2018 at 21:56
  • @ArchanJoshi: Try it, execute one and the other and you'll see. "sp_help" gives you information on PK's, constraints, while the other provides more information on the columns themselves Apr 17, 2018 at 13:48
  • 2
    syntax for a table in another schema sp_help 'schema.tablename' eg sp_help 'geo.test'
    – JohnC
    Sep 5, 2020 at 19:20
22

Try this query:

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

Output:

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)
)

Also read this:

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

5
  • 2
    In SSMS right-click table, select Script Table as > Create To > New Query Editor Window.
    – Rubio
    Dec 12, 2016 at 12:54
  • 1
    Didn't work for me. I don't have Sql Server Management Studio. All I have is the Azure Sql Query Editor. Jun 19, 2019 at 22:44
  • To use this to get a creation table script from a view just change the code at line 14 AND o.[type] = 'U' for this AND o.[type] in ('U', 'V')
    – gsubiran
    Sep 1, 2021 at 15:35
  • @Devart, you're a good man, sir Oct 22, 2021 at 15:31
  • would be great to get similar solution compatible on azure synapse dedicated sql pool Apr 25 at 12:51
18

On SQL Server 2012, you can use the following stored procedure:

sp_columns '<table name>'

For example, given a database table named users:

sp_columns 'users'
0
4

In SQL Server, you can use this query:

USE Database_name

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

And do not forget to replace Database_name and Table_name with the exact names of your database and table names.

3

For recent versions of SQL Server Management Studio Write the in a query editor and Do "Alt" + "F1"

1
  • I remembered this feature has been available since SQL 2005.
    – Ariwibawa
    Sep 7, 2021 at 2:47
0

Try this query:

select *
from (SELECT TABLE_SCHEMA
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME='brands')[.brands];
1
  • 2
    Your answer could be improved by adding more information on what the code does and how it helps the OP.
    – Tyler2P
    Aug 3, 2022 at 19:17
-1

To print a schema, I use jade and do an export to a file of the database then bring it into word to format and print

1
  • 4
    Please consider explaining your answer.
    – jpp
    Jan 1, 2019 at 0:52
-1

I was trying 'DESC table_name' but then this worked for me in psql:

select * 
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='table_name'; 
1
  • How does this differ from the already accepted answer?
    – baltermia
    May 26, 2021 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.