T-SQL query to show table definition?

后端 未结 16 1267
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 06:16

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

16条回答
  •  误落风尘
    2020-12-02 06:33

    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 " +
                         "     ");
                }
    
                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()
                    .Select(s => s + "\n" + "GO")
                    .ToList()
                    .ForEach(Console.WriteLine);
            }
        }
    }
    
        

    提交回复
    热议问题