SQL Server INSERT INTO with WHERE clause

后端 未结 7 1143
礼貌的吻别
礼貌的吻别 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'
    
    0 讨论(0)
  • 2021-01-05 06:00

    i do inserts into a table if the record doesn't exist this way. may not be entirely what is after but it may be helpful

    insert into x (a,b)
    select 1,2
    where 0=(select count(*) from x where a = 1 and b = 2)
    
    0 讨论(0)
  • 2021-01-05 06:03

    If you want to insert new rows with the given CustomerID

    INSERT
        INTO
            Payments(Amount,CustomerID )
    VALUES(12.33,'145300');
    

    else if you already have payment for the customer you can do:

    UPDATE
            Payments
    SET Amount = 12.33
    WHERE
        CustomerID = '145300';
    
    0 讨论(0)
  • 2021-01-05 06:07

    Do you want to perform update;

    update Payments set Amount  = 12.33 where Payments.CustomerID = '145300' 
    
    0 讨论(0)
  • 2021-01-05 06:09

    It sounds like having the customerID already set. In that case you should use an update statement to update a row. Insert statements will add a completely new row which can not contain a value.

    0 讨论(0)
  • 2021-01-05 06:10

    Better solution and without risk of deadlocks:

    UPDATE Payments
        SET Amount = 12.33
    WHERE CustomerID = '145300'
    
    INSERT INTO Payments(CustomerID,Amount)
        SELECT '145300',12.33
    WHERE @@ROWCOUNT=0
    
    0 讨论(0)
提交回复
热议问题