我有以下SQL查询:
SELECT v.PassNo, VName, e.eName, d.dtName, v.EntryTime
FROM Visitorlogo_tbl v
LEFT JOIN EmployeeMaster_tbl e ON v.empid=e.eId
JOIN DepartmentMaster_tbl d ON v.Deptid=d.dtId
WHERE v.EntryTime >= '2014-06-29'
我得到以下输出:
PassNo VName eName dtName EntryTime
100 jaseem null admin 2014-06-29 23:17:47.257
101 deepu sabu sales 2014-06-29 24:17:47.257
103 rabeeh null IT 2014-06-30 23:17:47.257
因为我想连接 ename
和 dtname
,我写了这样的查询:
SELECT v.PassNo AS 'Badge Id', VName AS VisitorName,
e.eName + ' ('+ d.dtName+')' AS 'Name(Department)', v.EntryTime
FROM Visitorlogo_tbl v
JOIN DepartmentMaster_tbl d ON v.Deptid = d.dtId
LEFT JOIN EmployeeMaster_tbl e ON v.empid = e.eId
WHERE v.EntryTime >= '2014-06-29'
但是,这会导致输出不匹配:
Badge Id VisitorName Name(Department) EntryTime
100 jaseem null 2014-06-29 23:17:47.257
101 deepu sabu 2014-06-29 24:17:47.257
103 rabeeh null 2014-06-30 23:17:47.257
为什么我看到NULL
而不是徽章ID 100
和103
的部门名称?
答案 0 :(得分:0)
连接字符串,其中一个字符串NULL
将始终产生NULL
。
例如:SELECT NULL + 'Moo'
将导致NULL
- 始终。
ISNULL()
接受2个参数,当第一个参数解析为NULL
时,将返回第二个参数 - BOL
你的意思是这样做吗?
SELECT [Badge Id] = v.PassNo
,VisitorName = VName
,[Name(Department)] = ISNULL(e.eName, '') + ISNULL(' (' + d.dtName + ')', '')
,v.EntryTime
FROM Visitorlogo_tbl V
JOIN DepartmentMaster_tbl D ON v.Deptid=d.dtId
LEFT
JOIN EmployeeMaster_tbl E ON v.empid=e.eId
WHERE v.EntryTime >= '2014-06-29'
答案 1 :(得分:0)
如果将null与任何内容连接起来,它将返回null。因此,您需要检查null以获得正确的结果。您可以使用以下查询
select v.PassNo as 'Badge Id',VName as VisitorName,ISNULL(e.eName,'') + ISNULL(' ('+ d.dtName+')','') as 'Name(Department)',v.EntryTime from Visitorlogo_tbl v
join DepartmentMaster_tbl d on v.Deptid=d.dtId
left join EmployeeMaster_tbl e on v.empid=e.eId
where v.EntryTime >='2014-06-29'
答案 2 :(得分:0)
SELECT v.PassNo as 'Badge Id',
VName as VisitorName,
ISNULL(e.eName,'') + ISNULL(' ('+ d.dtName+')','') as 'Name(Department)',
v.EntryTime
FROM Visitorlogo_tbl v
JOIN DepartmentMaster_tbl d on v.Deptid=d.dtId
LEFT JOIN EmployeeMaster_tbl e on v.empid=e.eId
WHERE v.EntryTime >='2014-06-29'