开发者

loop through numerous "if exists update, else insert" statements?

开发者 https://www.devze.com 2023-01-17 08:36 出处:网络
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?

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)开发者_StackOverflow中文版
    VALUES
    (value, value, value, value)


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


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.


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 (...)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号