我正在尝试使用此查询将一些模拟付款信息插入开发数据库:

INSERT
    INTO
        Payments(Amount)
    VALUES(12.33)
WHERE
    Payments.CustomerID = '145300';

如何调整此执行?我也尝试过这样的事情:
IF NOT EXISTS(
    SELECT
        1
    FROM
        Payments
    WHERE
        Payments.CustomerID = '145300'
) INSERT
    INTO
        Payments(Amount)
    VALUES(12.33);

最佳答案

我认为您正在尝试执行更新声明(对于ID = 145300的客户,设置金额= 12.33)

UPDATE Payments
SET Amount = 12.33
WHERE CustomerID = '145300'

否则,如果您要插入新行,则必须使用
IF NOT EXISTS(SELECT 1 FROM Payments WHERE CustomerID = '145300')
    INSERT INTO Payments(CustomerID,Amount)
    VALUES('145300',12.33)

或者,如果您想同时使用这两个命令(如果客户存在,请进行更新,否则插入新行)
IF NOT EXISTS(SELECT 1 FROM Payments WHERE CustomerID = '145300')
    INSERT INTO Payments(CustomerID,Amount)
    VALUES('145300',12.33)
ELSE
    UPDATE Payments
    SET Amount = 12.33
    WHERE CustomerID = '145300'

关于使用WHERE子句的SQL Server INSERT INTO,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48102013/

10-11 03:00