Создать таблицу в динамическом запросе - PullRequest
0 голосов
/ 08 мая 2019

У меня динамический запрос на создание таблицы с двумя полями. Первое поле от #Table, а второе (CreateDate) добавляется статическим способом.

if object_id(N'tempdb..#Table') is not null
    drop table #Table;

    create table #Table
    (

        [SchemaName] nvarchar(100) not null
        ,[TableName] nvarchar(128) not null
        ,[FieldId] int  
        ,[ColumnName] nvarchar(100)
        ,FieldDefinitionID int
        ,Ordinal int 
        ,[Data Type] nvarchar(100)
        ,IsNullable bit
        ,IsIdentity bit
        ,HasDefault bit 
        ,DefaultName nvarchar(100)
        ,DefaultDefinition  nvarchar(100)
        ,[Description] nvarchar(100) 
        ,HasCheckConstraint bit  
        ,CheckConstraintName bit 
        ,CheckConstraintDefinition bit 
        ,PartitionIndexKey bit 
        ,ObjectID int 


    );



    insert into #Table
                (
                    [SchemaName] 
                    ,[TableName] 
                    ,[FieldId]   
                    ,[ColumnName]   
                    ,Ordinal 
                    ,[Data Type] 
                    ,IsNullable 
                    ,IsIdentity
                    ,HasDefault 
                    ,HasCheckConstraint
                )
                select 
                N'dbo'
                ,N'test'
                ,-6
                ,N'RecordId'
                ,1
                ,N'int'
                ,0
                ,0
                ,0
                ,0






    insert into #Table
                (
                    [SchemaName] 
                    ,[TableName] 
                    ,[FieldId]   
                    ,[ColumnName]   
                    ,Ordinal 
                    ,[Data Type] 
                    ,IsNullable 
                    ,IsIdentity
                    ,HasDefault 
                    ,HasCheckConstraint
                )
                select 
                N'dbo'
                ,N'test'
                ,-6
                ,N'RecordId'
                ,1
                ,N'int'
                ,0
                ,0
                ,0
                ,0






select          N'

create table [' + [t].[SchemaName] + N'].[' + [t].[TableName] + N']
(
    [' 
    + [t].[ColumnName] 
    + N'] ' 
    + [t].[Data Type] 
    + case
        when [t].[IsNullable] = 0
        then N' not null '
        else N' null '
    end
    + case
        when [t].[IsIdentity] = 1
        then N' identity '
        else N''
    end
    + case
        when [t].[HasDefault] = 1
        then N' constraint [' + [t].[DefaultName] + N'] default ' + [t].[DefaultDefinition]
        else N''
    end
    +
    N'
    ,[CreateDate] datetime not null
);

exec sys.sp_addextendedproperty @name = N''EntityId''
                                ,@value = N''' + cast(11 as nvarchar(max)) + N'''
                                ,@level0type = N''Schema'', @level0name = N''' + [t].[SchemaName] + N'''
                                ,@level1type = N''Table'', @level1name = N''' + [t].[TableName] + N''';

exec sys.sp_addextendedproperty @name = N''MessageId''
                                ,@value = N''' + cast(3456 as nvarchar(max)) + N'''
                                ,@level0type = N''Schema'', @level0name = N''' + [t].[SchemaName] + N'''
                                ,@level1type = N''Table'', @level1name = N''' + [t].[TableName] + N''';

' 
from  #Table t

Итак, результатом является создание создания:

 create table [dbo].[test]
    (
        [RecordId] int not null 
        ,[CreateDate] datetime not null
    );

    exec sys.sp_addextendedproperty @name = N'EntityId'
                                    ,@value = N'11'
                                    ,@level0type = N'Schema', @level0name = N'dbo'
                                    ,@level1type = N'Table', @level1name = N'test';

    exec sys.sp_addextendedproperty @name = N'MessageId'
                                    ,@value = N'3456'
                                    ,@level0type = N'Schema', @level0name = N'dbo'
                                    ,@level1type = N'Table', @level1name = N'test';

Я хочу получить тот же результат, но мне нужно динамически получить второе поле из таблицы #Table, как и первое поле. Но я не знаю, как я могу это сделать.

Ответы [ 2 ]

0 голосов
/ 08 мая 2019

Пожалуйста, попробуйте это:

create table #Table
(
    [SchemaName] nvarchar(100) not null
    ,[TableName] nvarchar(128) not null
    ,[FieldId] int  
    ,[ColumnName] nvarchar(100)
    ,FieldDefinitionID int
    ,Ordinal int 
    ,[Data Type] nvarchar(100)
    ,IsNullable bit
    ,IsIdentity bit
    ,HasDefault bit 
    ,DefaultName nvarchar(100)
    ,DefaultDefinition  nvarchar(100)
    ,[Description] nvarchar(100) 
    ,HasCheckConstraint bit  
    ,CheckConstraintName bit 
    ,CheckConstraintDefinition bit 
    ,PartitionIndexKey bit 
    ,ObjectID int 
);
GO

insert into #Table
(
    [SchemaName] 
    ,[TableName] 
    ,[FieldId]   
    ,[ColumnName]   
    ,Ordinal 
    ,[Data Type] 
    ,IsNullable 
    ,IsIdentity
    ,HasDefault 
    ,HasCheckConstraint
)
values
(
    N'dbo'
    ,N'test'
    ,-6
    ,N'RecordId'
    ,1
    ,N'int'
    ,0
    ,0
    ,0
    ,0
);

insert into #Table
(
    [SchemaName] 
    ,[TableName] 
    ,[FieldId]   
    ,[ColumnName]   
    ,Ordinal 
    ,[Data Type] 
    ,IsNullable 
    ,IsIdentity
    ,HasDefault 
    ,HasCheckConstraint
)
values
(
    N'dbo'
    ,N'test'
    ,-6
    ,N'NewField'
    ,2
    ,N'NewFieldType'
    ,0
    ,0
    ,0
    ,0
);
GO

declare @NewLine nchar(2) = nchar(13) + nchar(10);

with [Tables] AS
(
    select distinct
        [SchemaName],
        [TableName],
        N'[' + [SchemaName] + N'].[' + [TableName] + N']' AS [FullTableName]
    from
        #Table
)
select
    N'create table ' + [FullTableName] + @NewLine +
    N'(' + @NewLine +
    N'    ' + REPLACE(STUFF((select
                                 N',[' + [ColumnName] + N'] '
                                 + [Data Type] +
                                 + case when [IsNullable] = 0 then N' not null' else N' null' end
                                 + case when [IsIdentity] = 1 then N' identity' else N'' end
                                 + case when [HasDefault] = 1 then N' constraint [' + [DefaultName] + N'] default ' + [DefaultDefinition] else N'' end
                             from
                                 #Table
                             where
                                 [SchemaName] = T.[SchemaName] AND
                                 [TableName] = T.[TableName]
                             order by
                                 [Ordinal]
                             for xml path('')
                            ), 1, 1, N''
                      ), N',', @NewLine + N'    ,') + @NewLine +
    N'    ,[CreateDate] datetime not null' + @NewLine +
    N');' + @NewLine +
    @NewLine +
    N'exec sys.sp_addextendedproperty @name = N''EntityId''' + @NewLine +
    N'                                ,@value = N''' + cast(11 as nvarchar(max)) + N'''' + @NewLine +
    N'                                ,@level0type = N''Schema'', @level0name = N''' + [t].[SchemaName] + N'''' + @NewLine +
    N'                                ,@level1type = N''Table'', @level1name = N''' + [t].[TableName] + N''';' + @NewLine +
    @NewLine +
    N'exec sys.sp_addextendedproperty @name = N''MessageId''' + @NewLine +
    N'                                ,@value = N''' + cast(3456 as nvarchar(max)) + N'''' + @NewLine +
    N'                                ,@level0type = N''Schema'', @level0name = N''' + [t].[SchemaName] + N'''' + @NewLine +
    N'                                ,@level1type = N''Table'', @level1name = N''' + [t].[TableName] + N''';' + @NewLine
from
    [Tables] as T
order by
    T.[SchemaName],
    T.[TableName];
0 голосов
/ 08 мая 2019

Добавьте запись в #Table с данными нового поля перед выполнением запроса.

Примерно так:

INSERT INTO #Table ([SchemaName], [TableName], [ColumnName], [Data Type])
VALUES ('dbo', 'Test', 'MyNewField', 'MyNewFieldType');

Вам необходимо заполнить правильные значениядля имени поля и его типа данных.При желании вам также может понадобиться установить явные значения для обнуляемости, идентичности, значения по умолчанию и т. Д.

Однако вы не указали структуру #Table.Я извлек поля из вашего запроса, но, возможно, вам потребуется также включить дополнительные поля.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...