Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Search for "Parent"

Author  Topic 

jtfadley
Starting Member

1 Post

Posted - 2011-09-22 : 19:37:17
So I need to update 3 columns with data from other columns in order to demonstrate relationships. My current table is something like the following:

<ID> <Description> <Parent> <OrgType>

With OrgTypes being Space, SpaceInput, Zone, Property, Class.

I need to add 3 more columns for <Space>, <Property>, and <Class> which will automatically populate in a SQL query based on a Parent's Parent, or a Parent's Grandparent...

So, for example, if the OrgType is Zone, I need to grab the Parent value, find where that Parent Value is in the ID column, and then return the corresponding value from the Parent column in that row.

A sample of what I've done so far is below:

UPDATE TABLENAME SET
PROPERTY = CASE
WHEN ORGTYPE = 'Space' THEN PARENTH1
WHEN ORGTYPE = 'Zone' THEN
(SELECT PARENT FROM TABLENAME WHERE ID = COLUMN_POPULATED_WITH_PARENT)
ELSE ''
END;

With that Select statement, though, it obviously brings me back a slew of records rather than looking through the table and finding out where this particular row's PARENT ID is.

Any recommendations? Thanks!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-22 : 22:52:14
you need to use recursive cte for this.
see
http://msdn.microsoft.com/en-us/library/ms186243.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -