I have (a more complex version of) the following schema:
CREATE TABLE Messages (
ItemId INT IDENTITY PRIMARY KEY,
Name VARCHAR(20) NOT NULL,
DeliveryType INT NOT NULL
);
CREATE TABLE NotificationsQueue (
ItemId INT NOT NULL,
DeliveryType INT NOT NULL
);
The possible values for DeliveryType are:
0 -> none
1 -> mail
2 -> email
3 -> both
Now, having some entries in the Messages table:
INSERT INTO Messages(Name, DeliveryType) Values
('Test0', 0),
('Test1', 1),
('Test2', 2),
('Test3', 3)
I need to populate the NotificationsQueue table like so:
- when DeliveryType = 0, don't insert anything
- when DeliveryType = 1 OR DeliveryType = 2, insert a tuple: (ItemId, DeliveryType)
- when DeliveryType = 3, insert two tuples: (ItemId, 1), (ItemId, 2)
My attempt to do so resulted in these two queries:
INSERT INTO NotificationsQueue (ItemId, DeliveryType) SELECT ItemId, 1 AS DeliveryType FROM Messages WHERE DeliveryType IN (1, 3)
INSERT INTO NotificationsQueue (ItemId, DeliveryType) SELECT ItemId, 2 AS DeliveryType FROM Messages WHERE DeliveryType IN (2, 3)
Even though this works, the select statements for the inserts are much more complex in practice, so I was wondering if there's any good way to merge them in a single query, in order to avoid duplication.
PS: I am not allowed to change the schema or add duplicate items in the Messages
table.