How to relate two rows with cyclic relationship in the same table in sql? I have a table on MS SQL Server 2008 R2 that consists of the following data:

+------+-------+-------------+----------+
| id   | type  | refer_to_id | group_id |
+------+-------+-------------+----------+
| 224  |     2 | 225         |          |
| 225  |     2 | 224         |          |
| 253  |     1 | 288         |          |
| 288  |     1 | 253         |          |
| 647  |     2 | ---         |          |
| 666  |     1 | 647         |          |
| 667  |     1 | 647         |          |
| 668  |     1 | 647         |          |
| 436  |     1 | ---         |          |
| 438  |     2 | 436         |          |
| 695  |     2 | 436         |          |
| 699  |     2 | 436         |          |
| 512  |     2 | ---         |          |
| 321  |     1 | ---         |          |
+------+-------+-------------+----------+


I need to update the column "group_id" as following:

+------+-------+-------------+----------+
| id   | type  | refer_to_id | group_id |
+------+-------+-------------+----------+
| 224  |     2 | 225         | 224      |
| 225  |     2 | 224         | 224      |
| 253  |     1 | 288         | 253      |
| 288  |     1 | 253         | 253      |
| 647  |     2 | ---         | 647      |
| 666  |     1 | 647         | 647      |
| 667  |     1 | 647         | 647      |
| 668  |     1 | 647         | 647      |
| 436  |     1 | 438         | 436      |
| 438  |     2 | 436         | 436      |
| 695  |     2 | 436         | 436      |
| 699  |     2 | 436         | 436      |
| 512  |     2 | ---         | 512      |
| 321  |     1 | ---         | 321      |
+------+-------+-------------+----------+


I would like the group_id to be the MIN(ID) between related rows.
Unfortunately I have cyclic relationship so I become crazy on writing T-SQL update statement.

How can I get this result?
I'm not sure to understand correctly your use case, but maybe you could simply do the update comparing refer_to_id and id columns.

update my_table
set group_id =  case when refer_to_id &gt; id then id 
                    when  refer_to_id &lt; id then refer_to_id 
                    else id 
                end


This is really basic and will not fix your issue if you have complex dependencies (line #1 referring to line #2 referring to line #3 etc...).