Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting column name dynamically in an insert query

Getting error Invalid column name '@ColumnNames'. in the last line (insert clause), any idea why ?

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
like image 328
DotNetJourneyMen Avatar asked Oct 28 '25 18:10

DotNetJourneyMen


2 Answers

@ColumnNames is a string of text, not a list of columns. As a result, when you try to use it as a list of column names in the insert query, it fails.

You can use dynamic SQL to do what you desire, like so:

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
like image 124
shree.pat18 Avatar answered Oct 31 '25 08:10

shree.pat18


You should use dynamic sql. And dont forget to perform data casting constructing query string!

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 );
like image 39
xacinay Avatar answered Oct 31 '25 08:10

xacinay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!