2017-08-08 82 views
0

我在存儲過程的工作,以顯示爲主的課程列表2個標準: 1.不需要courseid管理員 2.學生認爲確實需要courseId煉油SQL查詢 -

我已經使商店程序正常工作;但是,我想對其進行優化並使其更具可讀性。我添加了一個case語句,但出現錯誤「子查詢返回了多個值,這是不允許的」。我會很感激一些反饋。

DECLARE @ROLEID INT = 1; 
select * 
from Courses 
where courseID in (
    case when @ROLEID = 1 then (select coursedID From Department d where d.DepartmentName = 'Accounting') --a ROLEID 1 IS AN ADMINISTRATOR, so there will be several course ids returned 
    else (select coursedID From Department d where d.DepartmentName = 'Accounting' and d.CourseId = 'A101') 
) 

iF @ROLEID = 1) 
BEGIN 
    APPROPPRIATE QUERY HERE 
END ELSE 
BEGIN 
    APPROPPRIATE QUERY HERE 
END 
+1

深思更好:如何能在多個值數據集結果的行和列的特定交叉路口?另一種思考方式是提供一些相同的數據,並以表格的形式提供您期望在這種情況下看到的內容。如果不在表格中嵌入表格,您很快就會遇到麻煩。這就是編譯器不滿意的原因。 – xQbert

+1

'case'只適用於標量值,不適用於整個結果集。因此,當@ROLEID = 1時('...選擇查詢...')'時,它會根本不匹配,因爲'case'需要一個值,但返回的是一組完整的數據。 – Xedni

回答

2

case只適用於標量值,不適用於整個結果集。因此,當您執行case when @ROLEID = 1 then (...<select query>...)時,它基本上不匹配,因爲案件需要單個值,但返回的是完整的一組數據。

你可以把你的case語句在你的內部查詢

select * 
from Courses 
where CourseId in (select CourseId 
        from Department 
        where DepartmentName = 'Accounting' 
         and CourseId = case when @RoleId = 1 then CourseId else 'A101' end) 

或做這樣的

select * 
from Courses 
where CourseId in (select CourseId 
        from Department 
        where DepartmentName = 'Accounting' 
         and @RoleId = 1 or CourseId = 'A101') 

但兩者都受到越來越壞查詢計劃,因爲一個查詢將使用@RoleId另一個將使用列值。出於性能考慮,他們分裂成獨立的聲明可能是從長遠來看

if @RoleId = 1 
    select * 
    from courses 
    where DepartmentName = 'Accounting' 
else 
    select * 
    from courses 
    where CourseId = 'A101' 
     and DepartmentName = 'Accounting'