0

I am looking for a compact way to do this - insert multiple rows into a table with values from multiple columns of a row from another table. My destination table is really a list with a single column:

declare @stringList table
(
    val nvarchar(100)
)

This is how we can insert multiple rows:

INSERT INTO @stringList ( val ) VALUES
Val1, Val2, Val3, ...

This is how we insert from a select:

INSERT INTO @stringList 
SELECT col1 FROM table1 where id=something

But I cannot seem to find a way to use both at the same time.

I can select from one column:

insert into @stringList (val) 
select col1 from table1 where id=something

But it doesn't extend to multiple columns:

insert into @stringList (val) 
select col1, col2 from table1 where id=something

--The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.

I have tried various ways including using parentheses, but the syntax is not accepted:

insert into @stringList (val) 
(select col1 from table1 where id=something,
select  col2 from table1 where id=something

Any idea if what I want is doable?

1
  • You can use a cursor to get row level data from one table and insert into another table by using a loop. Commented Nov 19, 2020 at 17:50

1 Answer 1

3

You can unpivot using cross apply:

insert into @stringList (val) 
    select v.col
    from table1 t1 cross apply
         (values (t1.col1), (t1.col2)) v(col)
    where t1.id = something;
Sign up to request clarification or add additional context in comments.

2 Comments

My mind is blown. I did not know you could use values that way. So many wasted unions...
@DanielGimenez . . . This is also more efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.