Domanda

Come si scrive quanto segue in Microsoft SQL Server 2008?

IF EXISTS(SELECT * FROM Table WHERE Something=1000)
UPDATE Table SET Qty = Qty + 1 WHERE Something=1000
ELSE
INSERT INTO Table(Something,Qty) VALUES(1000,1)
È stato utile?

Soluzione

Utilizzando il nuovo comando merge in SQL Server 2008 sarebbe, per quanto ho potuto capire essere:

merge Table t
using (select 1000 as Something, 1 as Qty) s on t.Something = s.Something
when matched then
  update set t.Qty = t.Qty + 1
when not matched by target then
  insert values (s.Something, s.Qty);

Questo non è così semplice, come l'unione è più efficiente per la fusione set più grandi, non solo un singolo record. In caso contrario, si può solo tentare di aggiornare il record, e inserire uno se nessun record sono stati aggiornati:

update Table set Qty = Qty + 1 where Something = 1000
if (@@rowcount = 0) begin
  insert into Table (Something, Qty) values (1000, 1)
end

Altri suggerimenti

IF EXISTS(SELECT * FROM Table WHERE Something=1000)
BEGIN
 UPDATE Table SET Qty = Qty + 1 WHERE Something=1000
END
ELSE
BEGIN
 INSERT INTO Table(Something,Qty) VALUES(1000,1)
END
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top