如何在sql查询中使用大小写

时间:2015-05-20 13:43:40

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我的查询位于

之下
SELECT *, 
CASE WHEN SUBSTRING(controlId,1,1) = 'M' THEN (select fullname from master as controler 
where Regular.controlId = Master.MasterId)

WHEN SUBSTRING(controlId,1,1) = 'A' THEN (select fullname from Admin as controler 
where Regular.controlId = Master.AdminId)
END AS controler
FROM Regular
INNER JOIN Master ON Regular.ControlId = Master.MasterId 
INNER JOIN Admin ON Regular.ControlId = Admin.AdminId
Where (Regular.active=0)

我的表格

enter image description here

我的常规数据

enter image description here

我的主表

enter image description here

我的管理员表数据

enter image description here

我想从每一行的相关表中获取全名,但使用上面的代码却没有给出任何结果....

3 个答案:

答案 0 :(得分:2)

这些数据似乎很难正常化,并且问题中的信息不足以确定发生了什么,但我怀疑你的联接是错误的,你真的需要使用LEFT联接而不是INNER联接。然后你可以使用COALESCE()函数而不是CASE子句:

SELECT r.*, COALESCE(m.FullName, a.FullName, r.FullName) FullName 
FROM Regular r
LEFT JOIN Master m ON r.ControlId = m.MasterId 
LEFT JOIN Admin a ON r.ControlId = a.AdminId
WHERE r.active=0

答案 1 :(得分:1)

我无法使用INNER JOIN s

INNER JOIN Master ON Regular.ControlId = Master.MasterId 
INNER JOIN Admin ON Regular.ControlId = Admin.AdminId

Regular.ControlId不能同时存在于MasterAdmin

列中
SELECT *, 
CASE WHEN SUBSTRING(controlId,1,1) = 'M' THEN (select fullname from master as controler 
where Regular.controlId = Master.MasterId)

WHEN SUBSTRING(controlId,1,1) = 'A' THEN (select fullname from Admin as controler 
where Regular.controlId = Master.AdminId)
END AS controler
FROM Regular
Where (Regular.active=0)

答案 2 :(得分:1)

也许是因为内联。尝试更改为:

    SELECT *, 
    CASE WHEN SUBSTRING(controlId,1,1) = 'M' THEN (select top 1 fullname from Master
    where Regular.controlId = Master.MasterId)

    WHEN SUBSTRING(controlId,1,1) = 'A' THEN (select top 1 fullname from Admin
    where Regular.controlId = Admin.AdminId)
    END AS controler
    FROM Regular
    Where (Regular.active=0)