在SQL中使用带有左外部连接的case语句

时间:2017-12-12 22:45:42

标签: sql left-join case

我跟随2张桌子 table1

Id Name deptId
==============
1  a     d1
--------------
2  b     d2
--------------
3  c     null
--------------
4  d     d1
--------------

table2

deptId   d_name
==================
d1       accounts
------------------
d2       services
------------------

我正在使用SP工作,我可以为DeptName传递3个值中的任意一个('帐户','服务''所有' )

如果我通过了所有'我应该从table1获取所有记录(使用表2的左外连接,这意味着我应该看到记录 3 c null ) 对于其他两个值中的任何一个,我应该只得到table1中那些在table1中存在相应记录的记录

我使用了以下查询,但在d_name的特定值('帐户','服务')

的情况下,它不起作用
Select 
======
t1.Id, t1.name, t2.d_name
-------------------------
from 
====
table1 t1
----------
Left Outer Join 
===============
table2 t2 
----------
On t1.deptId = t2.deptId
------------------------
and table2.d_name =
-----------------
CASE WHEN @dname = 'All'
------------------------
    Then table2.d_name
----------------------
    Else @dname
------------------

@dname是传递给SP的参数值。目前它适用于'All'参数,但不适用于特定值('帐户'或'服务')。我不确定我在哪里出错

0 个答案:

没有答案