我正在查询结果我将其保存在名为@return的变量中
SELECT @return = THM.NAME
FROM Theme THM
LEFT JOIN ProductTheme PDT ON THM.PK_Theme = PDT.ThemeId
LEFT JOIN StoryProductTheme SPT ON PDT.PK_ProductTheme = SPT.ProductThemeId
LEFT JOIN Story STY ON SPT.StoryId = STY.PK_Story
WHERE STY.Number = @StoryNumber
AND (
THM.NAME = 'Adaptive'
OR THM.NAME = 'Corrective'
OR THM.NAME = 'Perfective'
OR THM.NAME = 'Preventive'
OR THM.NAME = 'New Development'
)
在某些情况下,我的列表中的多个将在普通查询中返回,其中结果未被分配给变量。在这种情况下,我希望“新发展”具有最低的预备。也就是说,如果返回任何其他4(自适应,纠正,完善,预防)以及'新开发',则4中的一个将被分配给变量。
我怎样才能做到这一点?
答案 0 :(得分:3)
建议拥有 PRIORITY 表!
SELECT TOP 1 @return = THM.NAME
FROM Theme THM
LEFT JOIN ProductTheme PDT ON THM.PK_Theme = PDT.ThemeId
LEFT JOIN StoryProductTheme SPT ON PDT.PK_ProductTheme = SPT.ProductThemeId
LEFT JOIN Story STY ON SPT.StoryId = STY.PK_Story
LEFT JOIN (SELECT 1 AS priority ,'Adaptive' as status_descr UNION ALL
SELECT 2,'Corrective' UNION ALL
SELECT 3,'Perfective' UNION ALL
SELECT 4,'Preventive' UNION ALL
SELECT 5,'New Development') AS MYPRIORITY
ON(MYPRIORITY.status_descr = THM.NAME)
WHERE STY.Number = @StoryNumber
ORDER BY MYPRIORITY.priority ASC
答案 1 :(得分:1)
有点快又脏。另一种选择是使用内部查询,但不容易写出来。如果你真的需要它,我也会花一些时间来搞清楚。
当存在多于1个结果时,此查询将首先返回自适应,然后是纠正,然后是完整,然后是预防,最后是新开发。
SELECT TOP 1 @return = THM.NAME
FROM Theme THM
LEFT JOIN ProductTheme PDT ON THM.PK_Theme = PDT.ThemeId
LEFT JOIN StoryProductTheme SPT ON PDT.PK_ProductTheme = SPT.ProductThemeId
LEFT JOIN Story STY ON SPT.StoryId = STY.PK_Story
WHERE STY.Number = @StoryNumber
AND THM.NAME IN ('Adaptive','Corrective','Perfective','Preventive','New Development')
ORDER BY
CASE THM.NAME WHEN 'Adaptive' THEN 1
WHEN 'Corrective' THEN 2
WHEN 'Perfective' THEN 3
WHEN 'Preventive' THEN 4
ELSE 6 END