views:

59

answers:

1
+2  Q: 

Query on Sql Joins

I have three tables.

tblLink: (LinkId, LinkName, GroupId, ,SubGroupId)
GroupId and SubGroupId are foreign key in tblGroup and tblSubGroup
tblGroup: (GroupId, GroupName)
tblSubGroup: (SubGroupId, SubGroupName)

in tblLink SubGroupId is allowed Null but GroupId is Mandatory.

I want to fetch LinkName, GroupName, SubGroupName for every LinkId in tblLink
I have written a query

SELECT L.LinkName, G.GroupName, SG.SubGroupName FROM tblLink L
Left Join
tblSubGroup SG
ON
(L.SubGroupId=SG.SubGroupId)
Inner Join
tblGroup G
ON
(L.GroupId=G.GroupId)

If there is no subgroup for some LinkId I want to show NotExist instead of Null

+4  A: 
SELECT
    L.LinkName, G.GroupName, 
    ISNULL(SG.SubGroupName, 'NotExist') AS SubGroupName
FROM
    Link L
....
gbn
You can use COALESCE to do that (instead of ISNULL), just makes your query more portable.
Technowise
@Technowise: beware implicit datatype conversion then... if SubGroupName is varchar(5) or char(50), it could be cast to varchar(8) to match the literal NotExist. With ISNULL it stays as per SubGroupName datatype. Portable SQL = changing contract?
gbn
@Technowise, what do you mean by portable here. What is COALESCE, Please Elaborate.
vaibhav
@gbn Thanks a lot, it worked fine.
vaibhav