Question

I have a table which consists of 100 columns based on a specific condition i want to generate only some of columns in insert statement.Right now my T-sql statement is hard-coded with certain columns. eg: The table has 100 columns but based on a condition i have insert only in specific colunms:

insert into temp (id,name,age,gender,contact) 
select * from #temp--temp table
Was it helpful?

Solution

Here is a fully working example:

create table temp (id int,name varchar(20),code int, morecolumns int) 
create table #temp(id int,name varchar(20),code int)

insert #temp values(1,'Thomas Clausen',1)

select * into xx_temp from #temp

declare @col varchar(max) , @sql varchar(max) = ''

select @col = coalesce(@col + ',', '')+ '[' + name + ']'
from tempdb.sys.columns 
where object_id = object_id('tempdb..#temp');

select @sql='insert temp(' + @col+ ') select '+@col+' from xx_temp'  

exec (@sql)
go
drop table xx_temp

There is a drawback, this example will create a table xx_temp and drop it right after executing. So the script should not execute more than once at a time. The table xx_table is created to get the data into the same scope inside the dynamic sql

OTHER TIPS

You might want to construct the query as string (varchar) and then execute it using -

Exec sp_executesql

For Example -

Declare @sql varchar(max)
SET @sql = 'insert into temp '

Now, you can add the names of the columns into @sql variable, depending upon your logic.

If you don't want to specify the columns you can do select into

SELECT * 
INTO newTable
FROM #source

This will do what you wanted but newTable table must not exist (this query will create the table). If you want to insert into existing you must specify the columns, and I'm sorry to say but EXEC of generated string query is the only way to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top