У меня динамический запрос на создание таблицы с двумя полями. Первое поле от #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, как и первое поле. Но я не знаю, как я могу это сделать.