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
@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
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 );
if you have to select all column from order table then there is no need to define @columnname