2015-04-14 191 views
2

TSQL Select子句我有一個讓我被存儲在數據庫中的類型列表的基本select語句:與Case語句

SELECT teType 
FROM BS_TrainingEvent_Types 
WHERE source = @source 
FOR XML PATH ('options'), TYPE, ELEMENTS, ROOT ('types') 

我的表包含一個類型列和源列。

該表中有一條記錄,我需要將它包含在兩個獨立的源中,但我無法爲其創建單獨的記錄。

**Table Data** 

type | source 
test  users 
test2  members 
test3  admins 

我需要一個case語句才能說IF source = admins also give me the type test2

這是否有意義,是否可以做一個基本的選擇?

更新 我想出了這個臨時解決辦法,但我仍然認爲這是一個更好的方式來處理這個問題:

DECLARE @tmp AS TABLE (
QID VARCHAR (10)); 

INSERT INTO @tmp (QID) 
SELECT DISTINCT qid 
FROM tfs_adhocpermissions; 

SELECT t.QID, 
     emp.FirstName, 
     emp.LastName, 
     emp.NTID, 
     (SELECT accessKey 
     FROM TFS_AdhocPermissions AS p 
     WHERE p.QID = t.QID 
     FOR XML PATH ('key'), TYPE, ELEMENTS, ROOT ('keys')) 
FROM @tmp AS t 
     LEFT OUTER JOIN 
     dbo.EmployeeTable AS emp 
     ON t.QID = emp.QID 
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root'); 
+0

僅供參考,它是CASE *表達式*,而不是CASE *語句*。 –

回答

0

試試這個

-------------------------------------------------------------------------------- 
-------------------------------------------------------------------------------- 
--create temp table for testing 
IF OBJECT_ID('Tempdb..#BS_TrainingEvent_Types') IS NOT NULL 
    DROP TABLE #BS_TrainingEvent_Types 
SELECT [type] , 
     [source] 
INTO #BS_TrainingEvent_Types 
FROM (VALUES ('test', 'users'), ('test2', 'members'), 
     ('test3', 'admins')) t ([type], [source]) 
-------------------------------------------------------------------------------- 
-------------------------------------------------------------------------------- 
--final query 
DECLARE @Source VARCHAR(10) = 'users' 

IF @Source = 'admins' 
    BEGIN 
     SELECT [Type] 
     FROM #BS_TrainingEvent_Types 
     WHERE source = @source 
       OR [type] = 'test2' 
     FOR  XML PATH('options') , 
        TYPE , 
        ELEMENTS , 
        ROOT('types') 
    END 
ELSE 
    BEGIN 
     SELECT [Type] 
     FROM #BS_TrainingEvent_Types 
     WHERE source = @source 
     FOR  XML PATH('options') , 
        TYPE , 
        ELEMENTS , 
        ROOT('types') 

    END 
0
select sq.teType 
from (
    SELECT t.teType 
    FROM BS_TrainingEvent_Types t 
    WHERE t.source = @source 
    union all 
    SELECT t.teType 
    FROM BS_TrainingEvent_Types t 
    WHERE @source = 'admins' and t.source = 'members' 
) sq 
FOR XML PATH ('options'), TYPE, ELEMENTS, ROOT ('types'); 

雖然正常最好引入一個可以存儲這些關係的附加表格,這樣整個想法就會更加豐富多彩即