136

What is a query that will show me the full definition, including indexes and keys for a SQL Server table? I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio. But SQLCMD is always an option.

UPDATE: I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime. Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

Colin 't Hart
  • 7,372
  • 3
  • 28
  • 51
Daniel Williams
  • 8,912
  • 15
  • 68
  • 107
  • 2
    What you're missing with `sp_help` is that it returns multiple result sets. You're describing the columns returned by the first result set. – Joe Stefanelli Jun 02 '11 at 14:40
  • 2
    Good question. Coming from MySQL, the solutions fall too short, for one can't see columns, indexes, foreign keys, constraint names all in one place. This is severe when you have many databases/tables in your object explorer. Hope Microsoft addresses this in the future. I haven't used any productivity tools but [SSMSBoost](http://www.ssmsboost.com/) looks promising. – peter n Oct 10 '13 at 15:28
  • 3
    @Microsoft please add DESC TABLE like MySQL. Easy. Simple. Done. – Pete Alvin May 08 '18 at 14:26

17 Answers17

152

There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.

SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'

SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')
Anthony Faull
  • 17,549
  • 5
  • 55
  • 73
  • 2
    Thank you. I was beginning to suspect that the only way to get this would be to query into a number of separate tables, and that it is what SQL Studio does when you tell it to "generate DDL". I'ma but surprised there is no general SP that will do it for you. – Daniel Williams Jun 02 '11 at 14:31
  • 7
    It is. If you want only the column info, you can execute `sp_columns` as I mentioned in my answer. If you want info about FKs run `sp_fkeys`. If you want to know indexes, execute `sp_statistics`. –  Jun 02 '11 at 16:12
84

Have you tried sp_help?

sp_help 'TableName'
SQLMenace
  • 132,095
  • 25
  • 206
  • 225
  • 1
    This shows structure, constraints, contraint types etc. Just one thing to note: you must write full name of the datatable. Schema.TableName. Otherwise, it completely solves the problem and gives all info about table. – FrenkyB Mar 09 '15 at 07:39
  • 3
    Does not return the DDL of the table, even with the full path written. – CoveGeek Feb 05 '16 at 22:14
31

Visit http://www.stormrage.com/SQLStuff/sp_GetDDL_Latest.txt.

You will find the code of sp_getddl procedure for SQL Server. The purpose of the procedure is script any table, temp table or object.

USAGE:

exec sp_GetDDL GMACT

or

exec sp_GetDDL 'bob.example'

or

exec sp_GetDDL '[schemaname].[tablename]'

or

exec sp_GetDDL #temp

I tested it on SQL Server 2012, and it does an excellent job.

I'm not the author of the procedure. Any improvement you make to it send to Lowell Izaguirre (scripts@stormrage.com).

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Dexter Vaca
  • 311
  • 3
  • 2
  • Thank you for this script and sharing! I would ask, do you have a post where we can discuss about this script? – Bellash Sep 21 '15 at 09:11
  • Excellent! MSFT must have such function inside Management Studio – Tertium Mar 19 '16 at 12:29
  • This did not work for me, it gives error message as, Msg 2812, Level 16, State 62, Line 74 Could not find stored procedure 'sp_GetDDL'. – yuvraj Dec 05 '21 at 06:20
  • @yuvraj, this is not a built-in procedure. You'll have to define it yourself using the code linked in the answer. – Sam Krygsheld Nov 18 '22 at 20:17
20

The easiest and quickest way I can think of would be to use sp_help

sp_help 'TableName'

codingbadger
  • 42,678
  • 13
  • 95
  • 110
18

Use this little Windows command-line app that gets the CREATE TABLE script (with constraints) for any table. I've written it in C#. Just compile it and carry it on a memory stick. Perhaps someone can port it to Powershell.

using System;
using System.Linq;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ViewSource
{
    public class ViewSource
    {
        public static void Main(string[] args)
        {
            if (args.Length != 6)
            {
                Console.Error.WriteLine("Syntax: ViewSource.exe <server>" +
                     " <user> <password> <database> <schema> <table>");
            }

            Script(args[0], args[1], args[2], args[3], args[4], args[5]);
        }
        private static void Script(string server, string user,
            string password, string database, string schema, string table)
        {
            new Server(new ServerConnection(server, user, password))
                .Databases[database]
                .Tables[table, schema]
                .Script(new ScriptingOptions { SchemaQualify = true,
                                               DriAll = true })
                .Cast<string>()
                .Select(s => s + "\n" + "GO")
                .ToList()
                .ForEach(Console.WriteLine);
        }
    }
}
Anthony Faull
  • 17,549
  • 5
  • 55
  • 73
17

Since SQL 2012 you can run the following statement:

Exec sp_describe_first_result_set @tsql= N'Select * from <yourtable>'

If you enter a complex select statement (joins, subselects, etc), it will give you the definition of the result set. This is very handy, if you need to create a new table (or temp table) and you don't want to check every single field definition manually.

https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-describe-first-result-set-transact-sql

Dan Stef
  • 753
  • 1
  • 10
  • 25
11

sp_help 'YourTableName'
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
7

I know it's an old question, but exactly what I was looking for. Because I want to batch script some tables, I rewrote the C# code from Anthony Faull for PowerShell.

This one is uses Integrated Security:

Import-Module sqlps

$serverInstance = "<server>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

And here with username and password:

Import-Module sqlps

$serverInstance = "<server>"
$user = "<user>"
$password = "<pasword>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$connection.LoginSecure = $false
$connection.Login = $user
$connection.Password = $password
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}
R. Horber
  • 480
  • 5
  • 11
7

This will return columns, datatypes, and indexes defined on the table:

--List all tables in DB
select * from sysobjects where xtype = 'U'

--Table Definition
sp_help TableName

This will return triggers defined on the table:

--Triggers in SQL Table
select * from sys.triggers where parent_id = object_id(N'SQLTableName') 
Nick Chammas
  • 11,843
  • 8
  • 56
  • 115
Siva
  • 2,791
  • 5
  • 29
  • 33
5

Simply type the table name and select it and press ATL + F1

Say your table name is Customer then open a new query window, type and select the table name and press ALT + F1

It will show the complete definition of table.

Ali Adravi
  • 21,707
  • 9
  • 87
  • 85
  • Good one )) But for me, it shows data for the whole database. I've tried new query windows with just table name in it and it doesn't work - it always shows everything. Otherwise, nice tip :) – FrenkyB Mar 09 '15 at 07:45
  • I used it with 2008 and 2012, not sure about the older versions, and it always works for me, Just the table name and ALT + F1, if want to use the schema then 'schema.table'. – Ali Adravi Mar 09 '15 at 19:15
  • 1
    It is the shortcut of sp_help 'schema.tablename' – Ali Adravi Mar 09 '15 at 19:17
  • 2
    Worked when I selected \ highlighted the table name. Showed entire database if there was anything else in the query window. – DB Tech Sep 07 '18 at 14:16
  • That just gets me a message about accessibility and screen-readers. – TextGeek Mar 14 '23 at 17:24
4

A variation of @Anthony Faull's answer for those using LINQPad:

new Server(new ServerConnection(this.Connection.DataSource))
    .Databases[this.Connection.Database]
    .Tables["<table>", "dbo"]
    ?.Script(new ScriptingOptions {
        SchemaQualify = true,
        DriAll = true,
    })

You'll need to reference 2 assemblies:

  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Smo.dll

And add namespace references as mentioned in Anthony's snippet.

Taras Strypko
  • 163
  • 1
  • 5
4
SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'EMPLOYEES'
Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498
3

Try the sp_help stored procedure.

sp_help <>

dotnetster
  • 1,601
  • 1
  • 16
  • 19
3

Another way is to execute sp_columns procedure.

EXEC sys.sp_columns @TABLE_NAME = 'YourTableName'
2

As an addition to Barry's answer. The sp_help can also be used by itself to iterate all of the objects in a particular database. You also have sp_helptext for your arsenal, which scripts out programmatic elements, like stored procedures.

Gregory A Beamer
  • 16,870
  • 3
  • 25
  • 32
2

General table definition is shown using stored procedure sp_help, as said before:

sp_help 'table_name_in_current_db_context'

When using tables of multiple contexts is useful to prefix the command above with the desired context, instead of changing them with use db_xyz:

DB_Products..sp_help 'MyTable' -- for definition of MyTable in DB_Products

And it works with temp tables also:

tempdb..sp_help '#TempTable' -- for definition of #TempTable in current context.

-1

There is an easy way to get DDL scripts for any database object.

  1. Open SQL Server Management Studio
  2. Connect to the source database server.
  3. Expand the databases tree.
  4. Right-click on the database with the tables to export.
  5. In the sub-menu, expand "Tasks".
  6. In the sub-menu, choose "Generate Scripts..."
  7. Use the wizard to choose the objects to export.
  8. For the scripting options, choose 1 script per object.

This will export a file for every table, view, stored proc, user, role, or schema you chose. Take that to the destination computer.

Bruce Dimon
  • 161
  • 10