I need a SQL query for the following COMPLEX task...
I need to to select from a column named parent_id
. If a row has 0 for parent_id
it means t
Using FOR XML EXPLICIT you can get a hierarchical list.
Try this:
SELECT
1 Tag,
null Parent,
'' [root!1!name],
null [category!2!id],
null [category!2!name],
null [rule!3!id],
null [rule!3!name]
UNION ALL
SELECT DISTINCT
2 Tag,
1 Parent,
null,
rule_id [category!2!id],
rule_title [category!2!name],
null [rule!3!id],
null [rule!3!name]
FROM rules
WHERE parent_id = 0 and rule_type = 'cat'
UNION ALL
SELECT
3 Tag,
2 Parent,
null,
parent_id [category!2!id],
null [category!2!name],
rule_id [rule!3!id],
rule_title [rule!3!name]
FROM rules
WHERE parent_id > 0 and rule_type = 'rule'
FOR XML EXPLICIT
For more information visit http://msdn.microsoft.com/en-us/library/ms189068.aspx