-1

Why does SQL Server not support to insert/update? It only supports select. Is there any alternative for In Duplicate Key of MySQL in SQL Server?

Please help..!

IF(SELECT accountNo 
   FROM MeterReading 
   WHERE accountNo = 1111) is NULL 
    (INSERT INTO dbo.MeterReading  
     VALUES (1, 1, 1, 1)); 
ELSE 
    (UPDATE dbo.MeterReading 
     SET currentReading = 1223 
     WHERE accountNo = 1111);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Why did you tag this question with java instead of sql-server? I don't see anything here that relates to java...? – azurefrog May 21 '18 at 16:21
  • 1
    Possible duplicate of [Solutions for INSERT OR UPDATE on SQL Server](https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server) – DavidG May 21 '18 at 16:38
  • in modern sqlserver versions it's called a [MERGE](https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-2017#a-using-merge-to-perform-insert-and-update-operations-on-a-table-in-a-single-statement) – fnostro May 21 '18 at 17:35
  • Does not make sense to not insert accountNo and currentReading. – paparazzo May 21 '18 at 17:45

3 Answers3

0

You could go for an UPSERT:

UPDATE MeterReading SET currentReading=1223 WHERE accountNo=1111

IF @@ROWCOUNT = 0
   INSERT INTO MeterReading VALUES (1, 1, 1, 1)
Daniel Almeida
  • 372
  • 1
  • 14
0

Try this syntax:

IF NOT EXISTS(SELECT accountNo 
               FROM MeterReading 
               WHERE accountNo = 1111) 
  BEGIN 
    INSERT INTO dbo.MeterReading  
    VALUES (1, 1, 1, 1) 
  END 
ELSE 
  BEGIN 
  UPDATE dbo.MeterReading 
  SET currentReading = 1223 
  WHERE accountNo = 1111
  END 
user7396598
  • 1,269
  • 9
  • 6
0

You could try Merge as well

MERGE MeterReading AS target  
    USING (SELECT 1111, 1223) AS source (accountNo, currentReading)  
    ON (target.accountNo = source.accountNo )  
WHEN MATCHED THEN   
    UPDATE SET currentReading  = source.currentReading   
WHEN NOT MATCHED THEN  
    INSERT (col1,col2,col3,col4)  
    VALUES (1, 1, 1, 1);
JamieD77
  • 13,796
  • 1
  • 17
  • 27