Question

Suppose I have the following insert statement for a table in my SQL Server 2008 DB:

INSERT INTO MyTable 
    ([Val1], [Val2], [Val3], [Val4])
VALUES
    ('val1', 'val2' 'val3', 'val4_a'),
    ('val1', 'val2' 'val3', 'val4_b'),
    ('val1', 'val2' 'val3', 'val4_c'),
    ('val1', 'val2' 'val3', 'val4_d');

In other words, all the values for [Val1] to [Val3] stay the same, but [Val4] keeps changing.

I was thinking to do something along the lines of:

Declare @Val1 varchar(10)
Declare @Val2 varchar(10)
Declare @Val3 varchar(10)   
Declare @Val4  ... some kind of list of varchar(10) ...

Set @Val1 = 'val1'
Set @Val2 = 'val2'
Set @Val3 = 'val3'
Set @Val4 = ('val4_a', 'val4_b', 'val4_c', 'val4_d')

and then do some kind of loop through @Val4 with only one insert statement to write in that case. This allows for very easy changing / updating and would make my life substantially easier!!

I know this won't work - I only put it in as an example of what I'm hoping to accomplish - but what would be the best way to do such a thing?

Thanks and I hope the question makes sense!!

Was it helpful?

Solution

You can write arbitrary queries for your INSERT, if you use SELECT instead of VALUES:

INSERT INTO MyTable 
    ([Val1], [Val2], [Val3], [Val4])
SELECT 'val1','val2','val3',v4.v
FROM (SELECT 'val4_a' union all
      SELECT 'val4_b' union all
      SELECT 'val4_c' union all
      SELECT 'val4_d') v4(v)

Of course, if you already have a table variable, say @v4 containing one row for each desired value, it's even easier:

INSERT INTO MyTable 
    ([Val1], [Val2], [Val3], [Val4])
SELECT 'val1','val2','val3',v4.v
FROM @v4 v4

And of course, then, it can insert 1 row, 4 rows, 100000 rows, however many you've put in @v4.


So, a complete script could be:

DECLARE @v4 table (v varchar(10) not null)
INSERT INTO @v4(v) VALUES ('val4_a'),('val4_b'),('val4_c'),('val4_d')

INSERT INTO MyTable 
    ([Val1], [Val2], [Val3], [Val4])
SELECT 'val1','val2','val3',v4.v
FROM @v4 v4

OTHER TIPS

You can use variables in the values statement. So:

INSERT INTO MyTable([Val1], [Val2], [Val3], [Val4])
VALUES
    (@val1, @val2, @val3, 'val4_a'),
    (@val1, @val2, @val3, 'val4_b'),
    (@val1, @val2, @val3, 'val4_c'),
    (@val1, @val2, @val3, 'val4_d');

Does that accomplish your goals?

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