programing

테이블 정의를 표시하는 T-SQL 쿼리?

nasanasas 2020. 8. 21. 07:51
반응형

테이블 정의를 표시하는 T-SQL 쿼리?


SQL Server 테이블의 인덱스 및 키를 포함하여 전체 정의를 표시하는 쿼리는 무엇입니까? 순수한 쿼리를 원하고 SQL Studio가이를 제공 할 수 있다는 것을 알고 있지만, 대부분의 기본 앱만있는 "와일드"컴퓨터에 있고 Studio를 설치할 권한이 없습니다. 그러나 SQLCMD는 항상 옵션입니다.

업데이트 : sp_help를 시도했지만 이름, 소유자, 유형 및 Created_Datetime을 보여주는 하나의 레코드 만 생성됩니다. sp_help에서 누락 된 다른 것이 있습니까?

내가 부르는 것은 다음과 같습니다.

sp_help 공항

테이블을 정의하는 DDL이 정말로 필요합니다.


DDL을 쉽게 반환 할 수있는 방법은 없습니다. 그러나 정보 스키마보기시스템보기 에서 대부분의 세부 정보를 얻을 수 있습니다 .

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

sp_help를 사용해 보셨습니까?

sp_help 'TableName'

http://www.stormrage.com/SQLStuff/sp_GetDDL_Latest.txt를 방문 하십시오 .

sp_getddlSQL Server에 대한 절차 코드를 찾을 수 있습니다. 절차의 목적은 모든 테이블, 임시 테이블 또는 개체를 스크립팅하는 것입니다.

용법:

exec sp_GetDDL GMACT

또는

exec sp_GetDDL 'bob.example'

또는

exec sp_GetDDL '[schemaname].[tablename]'

또는

exec sp_GetDDL #temp

SQL Server 2012에서 테스트했으며 훌륭한 작업을 수행합니다.

나는 절차의 저자가 아닙니다. 개선 사항은 Lowell Izaguirre (scripts@stormrage.com)로 보냅니다.


CREATE TABLE모든 테이블에 대한 스크립트 (제약 조건 포함)를 가져 오는이 작은 Windows 명령 줄 앱을 사용 합니다. C #으로 작성했습니다. 컴파일하고 메모리 스틱에 휴대하십시오. 누군가 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);
        }
    }
}

내가 생각할 수있는 가장 쉽고 빠른 방법은 sp_help 를 사용하는 것입니다.

sp_help 'TableName'


sp_help 'YourTableName'

이렇게하면 테이블에 정의 된 열, 데이터 유형 및 인덱스가 반환됩니다.

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

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://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-describe-first-result-set-transact-sql


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.


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.


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"}

Try the sp_help stored procedure.

sp_help <>


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.


Another way is to execute sp_columns procedure.

EXEC sys.sp_columns @TABLE_NAME = 'YourTableName'

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

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

use pg_dump:

pg_dump -s -t tablename dbname

It gives you the table definition (-s is schema only, no data) of a certain table ( -t tablename ) in database "dbname" in plain SQL. Additionally you will get sequence, primary key and constraint info. The output you can -maybe after checking and editing according to your needs- be fed again into (the same or another) Postgres database:

pg_dump -s -t tablename dbname1  > /tmp/foo.sql
psql -e dbname2 < /tmp/foo.sql

This is for UNIX/Linux, but I'm sure, that a pg_dump also exists for Windows.

참고URL : https://stackoverflow.com/questions/6215459/t-sql-query-to-show-table-definition

반응형