I have a question regarding performance of SQL Server.
Suppose I have a table persons
with the following columns: id
, name
, surname
.
Now, I want to insert a new row in this table. The rule is the following:
If id
is not present in the table, then insert the row.
If id
is present, then update.
I have two solutions here:
First:
update persons
set id=@p_id, name=@p_name, surname=@p_surname
where id=@p_id
if @@ROWCOUNT = 0
insert into persons(id, name, surname)
values (@p_id, @p_name, @p_surname)
Second:
if exists (select id from persons where id = @p_id)
update persons
set id=@p_id, name=@p_name, surname=@p_surname
where id=@p_id
else
insert into persons(id, name, surname)
values (@p_id, @p_name, @p_surname)
What is a better approach? It seems like in the second choice, to update a row, it has to be searched two times, whereas in the first option - just once. Are there any other solutions to the problem? I am using MS SQL 2000.
question from:
https://stackoverflow.com/questions/2275946/t-sql-insert-or-update 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…