Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not sure this can be done recursively with CTE in a nice way.</p> <p>But since you already have the LINK field in your table, you can use SQL code to fill out this field. You'll have to run the code every time the data has been changed:</p> <pre class="lang-sql prettyprint-override"><code>-- Reset LINK UPDATE LinkedRows SET LINK = NULL; -- Declare variables DECLARE @LinkCounter int; DECLARE @myID int; DECLARE @myCOL1 nvarchar(50); DECLARE @myCOL2 nvarchar(50); DECLARE @myLINK1 int; DECLARE @myLINK2 int; -- Init group counter SET @LinkCounter = 0; DECLARE RowCursor CURSOR FOR SELECT ID, COL1, COL2 FROM LinkedRows ORDER BY ID; OPEN RowCursor; -- Run through all records FETCH NEXT FROM RowCursor INTO @myID, @myCOL1, @myCOL2; WHILE @@FETCH_STATUS = 0 -- More records BEGIN DECLARE LinkCursor CURSOR FOR SELECT DISTINCT(LINK) FROM LinkedRows WHERE (COL1 = @myCOL1 OR COL1 = @myCOL2 OR COL2 = @myCOL1 OR COL2 = @myCOL2) AND NOT LINK IS NULL; OPEN LinkCursor; FETCH NEXT FROM LinkCursor INTO @myLINK1; IF @@FETCH_STATUS = 0 -- At least one record BEGIN FETCH NEXT FROM LinkCursor INTO @myLINK2; IF @@FETCH_STATUS = 0 -- Two records present - Link two groups BEGIN -- SELECT 'Link', @myLINK1, @myLINK2; -- Debug -- Join the groups - use the first LINK id UPDATE LinkedRows SET LINK = @myLINK1 WHERE LINK = @myLINK2; -- Add the new record to the group UPDATE LinkedRows SET LINK = @myLINK1 WHERE ID = @myID; END; ELSE -- Only one group - assign new record to existing group BEGIN -- SELECT 'Assign', @myLINK1; -- Debug UPDATE LinkedRows SET LINK = @myLINK1 WHERE ID = @myID; END; END; ELSE -- New group BEGIN SET @LinkCounter = @LinkCounter + 1; -- SELECT 'New', @LinkCounter; UPDATE LinkedRows SET LINK = @LinkCounter WHERE ID = @myID; END; CLOSE LinkCursor DEALLOCATE LinkCursor -- Get next record FETCH NEXT FROM RowCursor INTO @myID, @myCOL1, @myCOL2; END; CLOSE RowCursor; DEALLOCATE RowCursor; </code></pre> <p>Now the LINK field will contain the linked group.</p> <p><strong>EDITED</strong> Updated the code to handle the case where two groups would be joined, by a linking record.</p>
    singulars
    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