Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Given an item that should be in category X, once the category Y rows are already there you should be able to add the X with the code below. You'll need to adapt it to however you will be using it - in a cursor, as a set-based operation for all items with a category X row, or whatever.</p> <pre><code>DECLARE @y_id INT, @x_id INT, @item_id INT SELECT @y_id = category_id FROM dbo.Categories WHERE name = 'Y' SELECT @x_id = category_id FROM dbo.Categories WHERE name = 'X' SET @item_id = ??? ;WITH Begin_Dates AS (SELECT BI.item_id, BI.begin_date AS begin_date FROM Items BI WHERE NOT EXISTS (SELECT * FROM Item_Categories BIC2 WHERE BIC2.item_id = BI.item_id AND BIC2.category_id = @y_id AND BIC2.begin_date = BI.begin_date) UNION SELECT BIC1.item_id, end_date AS begin_date FROM Item_Categories BIC1 WHERE BIC1.category_id = @y_id AND NOT EXISTS (SELECT * FROM dbo.Items WHERE item_id = BIC1.item_id AND BIC1.end_date = end_date)), End_Dates AS (SELECT EI.item_id, EI.end_date AS end_date FROM Items EI WHERE NOT EXISTS (SELECT * FROM Item_Categories EIC2 WHERE EIC2.item_id = EI.item_id AND EIC2.category_id = @y_id AND EIC2.begin_date = EI.begin_date) UNION SELECT EIC1.item_id, begin_date AS end_date FROM Item_Categories EIC1 WHERE EIC1.category_id = @y_id AND NOT EXISTS (SELECT * FROM dbo.Items WHERE item_id = EIC1.item_id AND EIC1.begin_date = begin_date)) INSERT INTO dbo.Item_Categories ( item_id, category_id, begin_date, end_date ) SELECT @item_id, @x_id, BD.begin_date, ED.end_date FROM Begin_Dates BD INNER JOIN End_Dates ED ON ED.end_date &gt; BD.begin_date AND NOT EXISTS (SELECT * FROM End_Dates ED2 WHERE ED2.end_date &gt; BD.begin_date AND ED2.end_date &lt; ED.end_date) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload