[quoted text, click to view] On Fri, 18 Aug 2006 18:45:51 +0530, Veeraraje Urs wrote:
>Hi All
>
> I have a table with the data in the following format
> Col1 Col2 PoolID
> BOOK1 BOOK2 0
> BOOK3 BOOK1 0
> BOOK3 BOOK4 0
> BOOK5 BOOK6 0
>
>
>As per the above data our business logic says that
> Book1 is linked with Book2
> and Book3 is linked with Book1
> and Book3 is linked with Book4
>
>Since Book1 is linked with Book2 and
> Book1 is linked with Book3
>as per our business logic, Book2 is also linked with Book3
>
>So going by the above rule, Book1, Book2, Book3 and Book4 are linked each
>other.
>Our requirement is that we need to identify these interlinked items and
>update the poolid
>
>So the net result will be Book1, Book2, Book3 and Book4 will have a value of
>1
> and Book5 and Book6 will have a value of 2
Hi Veeraraje Urs,
Do the values have to be 1 and 2, or do they just have to be two
different values? In the latter case, try this:
WITH X (Col1, Col2, PoolID, rn)
AS (SELECT Col1, Col2, PoolID,
ROW_NUMBER() OVER (ORDER BY Col1, Col2) AS rn
FROM TABLE_A)
UPDATE X
SET PoolID = X.rn;
WHILE (@@ROWCOUNT > 0)
BEGIN;
UPDATE TABLE_A
SET PoolID = (SELECT MIN(x.PoolID)
FROM TABLE_A AS x
WHERE x.Col1 IN (TABLE_A.Col1, TABLE_A.Col2)
OR x.Col2 IN (TABLE_A.Col1, TABLE_A.Col2))
WHERE PoolID <> (SELECT MIN(x.PoolID)
FROM TABLE_A AS x
WHERE x.Col1 IN (TABLE_A.Col1, TABLE_A.Col2)
OR x.Col2 IN (TABLE_A.Col1, TABLE_A.Col2));
END;
The first part (which uses a SQL Server 2005 function - let me know if
you need a SQL Server 2000 equivalent) assigns a unique PoolID to each
row in the table. The next part (which should run on all versions of SQL
Server) replaces each PoolID with the lowest PoolID from any interlinked
item, and repeats this in a loop until no more changes are made.
--