Loop through numerous instructions "if exist update, else insert"?

I have a script that needs to insert 50+ rows into a table, is there a way for a loop, although every row I want to insert is instead of encoding 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)
+3
source share
3 answers

Even better, you can put records in a temporary table, then update everything existing and insert everything 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
+7
source

Well, SQL is a SET-based language, so you ideally keep it in a set. You can use a cursor for an iterative loop, but why?

MSDN:

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

Consider the operator MERGE(and, in particular, the first example on a linked page).

This allows you to define the operations to add, update, or delete when comparing the contents of the table and the selection request.

0
source

Source: https://habr.com/ru/post/1766052/


All Articles