SQL Server如果有,则插入/更新

时间:2018-05-21 16:17:38

标签: sql-server

为什么SQL Server不支持插入/更新?它只支持选择。 SQL Server中有In Duplicate Key MySQL的替代方法吗?

请帮忙..!

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);

3 个答案:

答案 0 :(得分:0)

你可以选择UPSERT:

UPDATE MeterReading SET currentReading=1223 WHERE accountNo=1111

IF @@ROWCOUNT = 0
   INSERT INTO MeterReading VALUES (1, 1, 1, 1)

答案 1 :(得分:0)

试试这个语法:

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 

答案 2 :(得分:0)

您也可以尝试合并

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);