I have SQL Server table structure like below:
ID Name ParentID
-----------------------
1 Root NULL
2 Business 1
3 Finance 1
4 Stock 3
I want to display the details in my web page like
ID Name ParentName
-------------------------
1 Root -
2 Business Root
3 Finance Root
4 Stock Finance
How can I construct my SQL query?
Child tables and parent tables are just normal database tables, but they're linked in a way that's described by a parent–child relationship. It's usually used to specify where one table's value refers to the value in another table (usually a primary key of another table). For example, imagine a news article.
To find out who that child's parent is, you have to look at the column parent_id , find the same ID number in the id column, and look in that row for the parent's name. In other words, Jim Cliffy has no parents in this table; the value in his parent_id column is NULL .
It depends. In general, you would like to have foreign key relationships. If there is only one comment allowed per question/answer, then it is easy. A commentId goes in each of the tables, Questions and Answers .
try this...
SELECT a.ID, a.Name, b.Name AS 'ParentName'
FROM TABLE AS a LEFT JOIN TABLE AS b on a.ParentID = b.ID
With the left join, the query will not find anything to join for the NULL and return blank for the ParentName
column.
EDIT:
If you do not want the 'Parent' column to be blank, but want to show a '-' dash then use this query.
SELECT a.ID, a.Name, COALESCE(b.Name,'-') AS 'ParentName'
FROM TABLE AS a LEFT JOIN TABLE AS b on a.ParentID = b.ID
Assuming SQL Server 2005+, use a recursive CTE like this:
WITH hierarchy AS (
SELECT t.id,
t.name,
t.parentid,
CAST(NULL AS VARCHAR(50)) AS parentname
FROM YOUR_TABLE t
WHERE t.parentid IS NULL
UNION ALL
SELECT x.id,
x.name,
x.parentid,
y.name
FROM YOUR_TABLE x
JOIN hierarchy y ON y.id = x.parentid)
SELECT s.id,
s.name,
s.parentname
FROM hierarchy s
The CASTing of the NULL might look odd, but SQL Server defaults the data type to INT unless specified in a manner like you see in my query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With