在工会内的情况?

时间:2011-11-11 21:34:40

标签: sql select union case

这是我的代码:

SELECT 'Add or remove a keyword' AS 'Keyword', '1' AS 'row number'
UNION
SELECT '---------------------', '2'
UNION
SELECT 
   CASE
   WHEN @list_item = 'duration'
   THEN (SELECT duration FROM durationTable)
   END
   CASE
   WHEN @list_item = 'location'
   THEN (SELECT location FROM locationTable)
   END
, '3'
ORDER BY 2

麻烦的是,这看到持续时间和位置选择为子查询,子查询仅限于一个结果,而且,我似乎无法找出正确的语法来将我的CASE提升到一个级别以便查询不是子查询。

有没有办法可以保留union / select允许的结构,同时还可以更改最后一位查询哪个表,还可以检索整个表列而不是一个结果?

任何提示?非常感谢你看看!

3 个答案:

答案 0 :(得分:2)

首先,您应该知道这是一个糟糕的设计。您正在混合表示层和数据层,这将导致问题。

但是,如果您绝对承诺这样做,您可以使用额外的SELECT

...
UNION

SELECT duration FROM durationTable, '3'
WHERE @list_item = 'duration'

UNION

SELECT location FROM locationTable, '3'
WHERE @list_item = 'location'
...

不匹配的查询将返回一个空结果集并被忽略。

答案 1 :(得分:0)

它不漂亮,但我认为这应该有效:

SELECT 'Add or remove a keyword' AS 'Keyword', '1' AS 'row number'
UNION
SELECT '---------------------', '2'
UNION
SELECT duration, '3' FROM durationTable WHERE 1 = (SELECT CASE WHEN @list_item = 'duration' THEN 1 ELSE 0 END)
UNION
SELECT location, '3' FROM locationTable WHERE 1 = (SELECT CASE WHEN @list_item = 'location' THEN 1 ELSE 0 END)

答案 2 :(得分:0)

SELECT 'Add or remove a keyword' AS 'Keyword', '1' AS 'row number'
UNION
SELECT '---------------------', '2'
UNION
SELECT duration,3 FROM durationTable WHERE @list_item = 'duration'
UNION
SELECT location,3 FROM locationTable WHERE @list_item = 'location'