Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server INSERT INTO with WHERE clause

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

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

How can adjust this to execute? I also tried something like this:

IF NOT EXISTS(
    SELECT
        1
    FROM
        Payments
    WHERE
        Payments.CustomerID = '145300' 
) INSERT 
    INTO
        Payments(Amount)
    VALUES(12.33);
like image 752
Matt Larson Avatar asked Jan 04 '18 19:01

Matt Larson


Video Answer


3 Answers

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'
like image 70
Hadi Avatar answered Sep 29 '22 12:09

Hadi


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';
like image 41
TheOni Avatar answered Sep 29 '22 13:09

TheOni


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.

like image 25
Frank Förster Avatar answered Sep 29 '22 13:09

Frank Förster