获取表结构的sql

EXEC GetTableScript ‘frmuser‘

CREATE PROCEDURE GetTableScript
@TableName VARCHAR(50)
AS 

--To get table script
declare @Id int, @i int, @i2 int,@Sql varchar(max),@Sql2 varchar(max), @f1 varchar(5), @f2 varchar(5), @f3 varchar(5), @f4 varchar(5), @T varchar(5)
    select @Id=object_id(@TableName), @f1 = char(13) + char(10), @f2 = ‘    ‘, @[email protected][email protected], @f4=‘,‘ + @f3

    if not(@Id is null)
    BEGIN
    declare @Data table(Id int identity primary key, D varchar(max) not null, ic int null, re int null, o int not null);

    -- Columns
    with c as(
        select c.column_id, Nr = row_number() over(order by c.column_id), Clr=count(*) over(),
            D = quotename(c.name) + ‘ ‘ +
                case when s.name = ‘sys‘ or c.is_computed=1 then ‘‘ else quotename(s.name) + ‘.‘ end +
                case when c.is_computed=1 then ‘‘ when s.name = ‘sys‘ then t.Name else quotename(t.name) end +
                case when c.user_type_id!=c.system_type_id or c.is_computed=1 then ‘‘
                    when t.Name in (‘xml‘, ‘uniqueidentifier‘, ‘tinyint‘, ‘timestamp‘, ‘time‘, ‘text‘, ‘sysname‘, ‘sql_variant‘, ‘smallmoney‘, ‘smallint‘, ‘smalldatetime‘, ‘ntext‘, ‘money‘,
                                    ‘int‘, ‘image‘, ‘hierarchyid‘, ‘geometry‘, ‘geography‘, ‘float‘, ‘datetimeoffset‘, ‘datetime2‘, ‘datetime‘, ‘date‘, ‘bigint‘, ‘bit‘) then ‘‘
                    when t.Name in(‘varchar‘,‘varbinary‘, ‘real‘, ‘numeric‘, ‘decimal‘, ‘char‘, ‘binary‘)
                        then ‘(‘ + isnull(convert(varchar,nullif(c.max_length,-1)), ‘max‘) + isnull(‘,‘+convert(varchar,nullif(c.scale, 0)), ‘‘) + ‘)‘
                    when t.Name in(‘nvarchar‘,‘nchar‘)
                        then ‘(‘ + isnull(convert(varchar,nullif(c.max_length,-1) / 2), ‘max‘) + isnull(‘,‘+convert(varchar,nullif(c.scale, 0)), ‘‘) + ‘)‘
                    else ‘??‘
                    end +
                case when ic.object_id is not null then ‘ identity(‘ + convert(varchar,ic.seed_value) + ‘,‘ + convert(varchar,ic.increment_value) + ‘)‘ else ‘‘ end +
                case when c.is_computed=1 then ‘as‘ + cc.definition when c.is_nullable = 1 then ‘ null‘ else ‘ not null‘ end +
                case c.is_rowguidcol when 1 then ‘ rowguidcol‘ else ‘‘ end +
                case when d.object_id is not null then ‘ default ‘ + d.definition else  ‘‘ end
        from sys.columns c
        inner join sys.types t
        on t.user_type_id = c.user_type_id
        inner join sys.schemas s
        on s.schema_id=t.schema_id
        left outer join sys.computed_columns cc
        on cc.object_id=c.object_id and cc.column_id=c.column_id
        left outer join sys.default_constraints d
        on [email protected] and d.parent_column_id=c.column_id
        left outer join sys.identity_columns ic
        on ic.object_id=c.object_id and ic.column_id=c.column_id
        where [email protected]

    )
        insert into @Data(D, o)
        select ‘    ‘ + D + case Nr when Clr then ‘‘ else ‘,‘ + @f1 end, 0
        from c where NOT D IS NULL
        order by column_id

    -- SubObjects
    set @i=0
    while 1=1
        begin
        select top 1 @i=c.object_id, @T = c.type, @i2=i.index_id
        from sys.objects c
        left outer join sys.indexes i
        on [email protected] and i.name=c.name
        where [email protected] and c.object_id>@i and c.type not in(‘D‘)
        order by c.object_id
        if @@rowcount=0 break
        if @T = ‘C‘
            insert into @Data
            select @f4 + ‘check ‘ + case is_not_for_replication when 1 then ‘not for replication ‘ else ‘‘ end + definition, null, null, 10
            from sys.check_constraints where [email protected]
        else if @T = ‘Pk‘
            insert into @Data
            select @f4 + ‘primary key‘ + isnull(‘ ‘ + nullif(lower(i.type_desc),‘clustered‘), ‘‘), @i2, null, 20
            from sys.indexes i
            where [email protected] and [email protected]
        else if @T = ‘uq‘
            insert into @Data values(@f4 + ‘unique‘, @i2, null, 30)
        else if @T = ‘f‘
            begin
            insert into @Data
            select @f4 + ‘foreign key‘, -1, @i, 40
            from sys.foreign_keys f
            where [email protected]

            insert into @Data
            select ‘ references ‘ + quotename(s.name) + ‘.‘ + quotename(o.name), -2, @i, 41
            from sys.foreign_keys f
            inner join sys.objects o
            on o.object_id=f.referenced_object_id
            inner join sys.schemas s
            on s.schema_id=o.schema_id
            where [email protected]

            insert into @Data
            select ‘ not for replication‘, -3, @i, 42
            from sys.foreign_keys f
            inner join sys.objects o
            on o.object_id=f.referenced_object_id
            inner join sys.schemas s
            on s.schema_id=o.schema_id
            where [email protected] and f.is_not_for_replication=1
            end
        else
            insert into @Data values(@f4 + ‘Unknow SubObject [‘ + @T + ‘]‘, null, null, 99)
        end

    insert into @Data values(@f1+‘)‘, null, null, 100)

    -- Indexes
    insert into @Data
    select @f1 + ‘create ‘ + case is_unique when 1 then ‘unique ‘ else ‘‘ end + lower(s.type_desc) + ‘ index ‘ + ‘i‘ + convert(varchar, row_number() over(order by index_id)) + ‘ on ‘ + quotename(sc.Name) + ‘.‘ + quotename(o.name), index_id, null, 1000
    from sys.indexes s
    inner join sys.objects o
    on o.object_id=s.object_id
    inner join sys.schemas sc
    on sc.schema_id=o.schema_id
    where [email protected] and is_unique_constraint=0 and is_primary_key=0 and s.type_desc != ‘heap‘

    -- columns
    set @i=0
    while 1=1
        begin
        select top 1 @i=ic from @Data where ic>@i order by ic
        if @@rowcount=0 break
        select @i2=0, @Sql=null, @Sql2=null
        while 1=1
            begin
            select @i2=index_column_id,
                @Sql = case c.is_included_column when 1 then @Sql else isnull(@Sql + ‘, ‘, ‘(‘) + cc.Name + case c.is_descending_key when 1  then ‘ desc‘ else ‘‘ end end,
                @Sql2 = case c.is_included_column when 0 then @Sql2 else isnull(@Sql2 + ‘, ‘, ‘(‘) + cc.Name + case c.is_descending_key when 1  then ‘ desc‘ else ‘‘ end end
            from sys.index_columns c
            inner join sys.columns cc
            on c.column_id=cc.column_id and cc.object_id=c.object_id
            where [email protected] and [email protected] and index_column_id>@i2
            order by index_column_id
            if @@rowcount=0 break
            end
        update @Data set [email protected] +‘)‘ + isnull(‘ include‘ + @Sql2 + ‘)‘, ‘‘) where [email protected]
        end

    -- references
    set @i=0
    while 1=1
        begin
        select top 1 @i=re from @Data where re>@i order by re
        if @@rowcount=0 break

        select @i2=0, @Sql=null, @Sql2=null
        while 1=1
            begin
            select @i2=f.constraint_column_id,
                @Sql = isnull(@Sql + ‘, ‘, ‘(‘) + c1.Name,
                @Sql2 = isnull(@Sql2 + ‘, ‘, ‘(‘) + c2.Name
            from sys.foreign_key_columns f
            inner join sys.columns c1
            on c1.column_id=f.parent_column_id and c1.object_id=f.parent_object_id
            inner join sys.columns c2
            on c2.column_id=f.referenced_column_id and c2.object_id=f.referenced_object_id
            where [email protected] and f.constraint_column_id>@i2
            order by f.constraint_column_id
            if @@rowcount=0 break
            end
        update @Data set D = D + @Sql + ‘)‘  where [email protected] and ic=-1
        update @Data set D = D + @Sql2 + ‘)‘  where [email protected] and ic=-2
        end;

    -- Render
    with x as(
        select id=d.id-1, D=d.D + isnull(d2.D,‘‘)
        from @Data d
        left outer join @Data d2
        on d.re=d2.re and d2.o=42
        where d.o=41

    )
    update @Data
        set D=d.D+x.D
    from @Data d
    inner join x
    on x.id=d.id

    delete @Data where o in(41, 42)

    select @Sql = ‘create table ‘ + quotename(s.name) + ‘.‘ + quotename(o.name) + ‘(‘ + @f1
    from sys.objects o
    inner join sys.schemas s
    on o.schema_id = s.schema_id
    where [email protected]

    set @i=0
    while 1=1
        begin
        select top 1 @I=Id, @Sql = @Sql + D from @Data order by o, case when o=0 then right(‘0000‘ + convert(varchar,id),5)  else D end, id
        if @@rowcount=0 break
        delete @Data where [email protected]
        end
    END
    SELECT @Sql
时间: 2024-10-05 16:14:41

获取表结构的sql的相关文章

SQL Server2008中通过SQL获取表结构

SQL Server2008中通过SQL获取表结构 新增数据用户,角色为public.映射到待获取表结构的数据库上,授与用户在该数据库上的身份为db_owner 运行例如以下SQL语句: select syscolumns.name as [Name] , systypes.name as [Type], syscolumns.length AS [Size], syscolumns.xprec As [Precision], ISNULL(syscolumns.scale, 0) AS [Sc

SQLServer2005,2000获取表结构:字段名、类型、长度、主键、非空、注释

SQLServer 2005 SELECT d.name N'TableName', d.xtype N'TableType', a.colorder N'ColumnIndex', a.name N'ColumnName', (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '1'else '0' end) N'IdnetityFG', (case when (SELECT count(*) FROM sysobjects

Oracle获取表结构信息:表名、是否视图、字段名、类型、长度、非空、主键

select a.TABLE_NAME as "TableName", case when (select count(*) from user_views v where v.VIEW_NAME =a.TABLE_NAME )>0 then 'V' else 'U'end as "TableType", a.COLUMN_NAME as "ColumnName", A.COLUMN_ID as "ColumnIndex"

读数据库所有表和表结构的sql语句

SQL获取所有数据库名.表名.储存过程以及参数列表 1.获取所有用户名:SELECT name FROM Sysusers where status='2' and islogin='1'islogin='1'表示帐户islogin='0'表示角色status='2'表示用户帐户status='0'表示糸统帐户2.获取所有数据库名:SELECT Name FROM Master..SysDatabases ORDER BY Name3.获取所有表名SELECT Name FROM Databas

SqlServer获取表结构语句

--sql server 2005-- 1. 表结构信息查询 -- ========================================================================-- 表结构信息查询-- 邹建 2005.08(引用请保留此信息)-- ========================================================================SELECT TableName=CASE WHEN C.column_

Sql中获取表结构(字段名称,类型,长度,说明)

在写代码生成器的时候遇到这样一个问题,想在搭建好数据库后把字段说明当做注释写进类文件里,所以我们在网上搜索到了许多代码很长很长的方法(当然我的代码也很长),亲测了一条简单易懂的语句,也是大多数转载的方法: SELECT TableName = OBJECT_NAME(c.object_id), ColumnsName = c.name, Description = ex.value, ColumnType=t.name, Length=c.max_length FROM sys.columns

sql获取表结构

SELECT a.name 字段名, (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then 1 ELSE 0 end) 标识, (case when (SELECT count(*) FROM dbo.sysobjects WHERE (name in (SELECT name FROM dbo.sysindexes WHERE (id = a.id) AND (indid in (SELECT indid FROM dbo.sy

mssql 获取表结构信息

SELECT (case when a.colorder=1 then d.name else null end) 表名, a.colorder 字段序号,a.name 字段名, (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) 标识, (case when (SELECT count(*) FROM sysobjects WHERE (name in (SELECT name FROM sys

Sql Server 导出数据库表结构的SQL查询语句

1 --导出数据库所有表 2 3 SELECT 4 表名 = Case When A.colorder=1 Then D.name Else '' End, 5 表说明 = Case When A.colorder=1 Then isnull(F.value,'') Else '' End, 6 字段序号 = A.colorder, 7 字段名 = A.name, 8 字段说明 = isnull(G.[value],''), 9 标识 = Case When COLUMNPROPERTY( A.