Reputation: 79
It is pretty straight forward, but I could not find an answer. If the combination does exist, then UPDATE, else INSERT.
IF EXISTS(SELECT customer_id FROM payment_conditions WHERE customer_id = 2 AND shipping_company_id = 1)
THEN
UPDATE payment_conditions SET payment_condition = "pay in full" WHERE customer_id = 2 AND shipping_company_id = 1;
ELSE
INSERT INTO payment_conditions customer_id, shipping_company_id, payment_condition, active VALUES (2,1,"some value",1);
END IF
Upvotes: 1
Views: 3169
Reputation: 38
Use the merge statement in SQL Server - it looks like these answers imply MySQL syntax. You don't state the database flavor, but Merge is the recommended way to do this on SQL Server.
Upvotes: 0
Reputation: 17831
You should set customer_id
and shipping_company_id
to be foreign keys, so you can use
INSERT INTO payment_conditions
customer_id, shipping_company_id, payment_condition, active
VALUES (2, 1, "some value", 1)
ON DUPLICATE KEY UPDATE payment_condition = "pay in full"
Upvotes: 2
Reputation: 22925
Or issue two statements (N.B. with UPDATE first), and do away with the conditional logic. The UPDATE will have no effect if the row does not exist. This should work if your key happens to be different to the customer_id + shipping_company.
UPDATE payment_conditions SET payment_condition = "pay in full"
WHERE customer_id = 2 AND shipping_company_id = 1;
then
INSERT INTO payment_conditions
(customer_id
, shipping_company_id
, payment_condition
, active)
VALUES (2,1,"some value",1)
where not exists
(select * FROM payment_conditions
WHERE customer_id = 2 AND shipping_company_id = 1);
Upvotes: 1
Reputation: 204894
INSERT INTO payment_conditions (customer_id, shipping_company_id, payment_condition, active)
VALUES (2,1,"some value",1)
ON DUPLICATE KEY UPDATE payment_condition = "pay in full"
Upvotes: 1
Reputation: 5846
if you have a unique key on (shipping_company_id, customer_id) you can use:
INSERT INTO payment_conditions
SET customer_id = 2,
shipping_company_id = 1,
payment_condition = 'some value',
active = 1
ON DUPLICATE KEY UPDATE payment_condition = 'pay in full'
Upvotes: 2