在插入查询中动态选择列名

时间:2014-05-27 09:05:23

标签: sql sql-server tsql dynamic-sql

获取错误列名称无效' @ ColumnNames'。在最后一行(插入子句),任何想法为什么?

Declare @ColumnNames varchar(2000)
Declare @OrderId int
set @OrderId = 110077

select @ColumnNames = COALESCE(@ColumnNames + ', ', '') + COLUMN_NAME
    from 
        INFORMATION_SCHEMA.COLUMNS
    where 
        TABLE_NAME='OrderItems'

Insert into dbo.OrderHistory(@ColumnNames) select * from dbo.[Order] where ID= @OrderId

3 个答案:

答案 0 :(得分:5)

@ColumnNames是一个文本字符串,而不是列的列表。因此,当您尝试将其用作插入查询中的列名列表时,它将失败。

您可以使用动态SQL来执行您想要的操作,例如:

declare @insertquery nvarchar(1000)
set @insertquery = N'insert into dbo.orderhistory(' + @ColumnNames + ') select * from dbo.[Order] where ID=' + cast(@OrderId as nvarchar(10))

sp_executesql @insertquery

答案 1 :(得分:2)

你应该使用动态sql。并且不要忘记执行数据构建构建查询字符串!

Declare @ColumnNames varchar(2000)
Declare @OrderId int
set @OrderId = 110077

select @ColumnNames = COALESCE(@ColumnNames + ', ', '') + COLUMN_NAME
    from 
        INFORMATION_SCHEMA.COLUMNS
    where 
        TABLE_NAME='OrderItems'
Declare @DynSqlStatement varchar(max);
set @DynSqlStatement = 'Insert into dbo.OrderHistory('+ @ColumnNames + ') 
      select * from dbo.[Order] where ID= ' + cast(@OrderId as varchar(10));
exec( @DynSqlStatement );

答案 2 :(得分:-1)

如果您必须从订单表中选择所有列,则无需定义@columnname