SQL Server INSERT INTO with WHERE clause

后端 未结 7 1145
礼貌的吻别
礼貌的吻别 2021-01-05 05:39

I\'m trying to insert some mock payment info into a dev database with this query:

INSERT
    INTO
        Payments(Amount)
    VALUES(12.33)
WHERE
    Paymen         


        
7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 06:00

    I think you are trying to do an update statement (set amount = 12.33 for customer with ID = 145300)

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

    Else if you are trying to insert a new row then you have to use

    IF NOT EXISTS(SELECT 1 FROM Payments WHERE CustomerID = '145300')
        INSERT INTO Payments(CustomerID,Amount)
        VALUES('145300',12.33)
    

    Or if you want to combine both command (if customer exists do update else insert new row)

    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'
    

提交回复
热议问题