views:

52

answers:

3

I have a script that needs to insert 50+ rows into a table, is there a way to loop though each row I want to insert, rather than coding this below statement 50 + times in TSQL?

IFEXISTS ( SELECT 1 FROM table where column 1 = )
    UPDATE table
    Column1 = value,
    Column2 = value,
    Column3 = value,
    Column4 = value
    WHERE column 1 =
    ELSE
    INSERT INTO table
    (Column1, Column2, Column3, Column4)
    VALUES
    (value, value, value, value)
A: 

Well, SQL is a SET based language so ideally you keep it in a set. To iteratively loop you could use a cursor, but why?

Here is another approach off of an MSDN blog:

UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
    INSERT INTO Table1 VALUES (...)
Dustin Laine
A: 

Consider the MERGE statement (and specifically the first example on the linked page).

This allows you to define operations for add, update or remove when comparing the content of a table and a select query.

Richard
+5  A: 

Even better, you can put the records in a temporary table, then update all that exists and insert all that doesn't exist with two queries.

Example:

select Column1 = 1, Column2 = 2, Column3 = 3
into #temp
union all select 1,2,3
union all select 1,2,3
union all select 1,2,3
...
union all select 1,2,3

update t
set Column1 = p.Column1, Column2 = p.Column2, Column3 = p.Column3
from table t
inner join #temp p on p.Column1 = t.Column1

insert into table (Column1, Column2, Column3)
select p.Column1, p.Column2, p.Column3
from #temp p
left join table t on t.Column1 = p.Column1
where t.Column1 is null

drop table #temp
Guffa
Tested this with a few rows and seems to work fantastic. Thank you much for this.