将多个 CASE 语句合并为一个并 SELECT INTO 临时表
Posted
技术标签:
【中文标题】将多个 CASE 语句合并为一个并 SELECT INTO 临时表【英文标题】:Combine multiple CASE statements into one and SELECT INTO temp table 【发布时间】:2014-06-02 17:24:42 【问题描述】:我有一个产生单独输出的查询。我需要将 SELECT CASE 语句合并为一个,然后将所有输出插入到临时表中
SELECT CASE WHEN #WCV_3.VISIT_1 IS NULL THEN '' ELSE CONVERT(VARCHAR(10), #WCV_3.VISIT_1,110) END
FROM #WCV_3
SELECT CASE WHEN #WCV_3.VISIT_2 IS NULL THEN '' ELSE CONVERT(VARCHAR(10), #WCV_3.VISIT_2,110) END
FROM #WCV_3
等等……
SELECT CASE WHEN #WCV_3.VISIT_5 IS NULL THEN '' ELSE CONVERT(VARCHAR(10),
#WCV_3.VISIT_5, 110) END
FROM #WCV_3
我试过了
SELECT * INTO
#WCV_4 (this is my new temp table)
FROM
(
SELECT CASE WHEN #WCV_3.VISIT_1 IS NULL THEN '' ELSE CONVERT(VARCHAR(10), #WCV_3.VISIT_1,110) END
FROM #WCV_3
etc... END)
但出现2个错误:
“关键字'SELECT'附近的语法不正确”
与
“')'附近的语法不正确”
`
【问题讨论】:
把UNION ALL
放在这些语句之间。
【参考方案1】:
您的查询应如下所示:
SELECT SomeColumn
INTO #WCV_4
FROM (
SELECT CASE WHEN #WCV_3.VISIT_1 IS NULL THEN '' ELSE CONVERT(VARCHAR(10), #WCV_3.VISIT_1,110) END AS SomeColumn FROM #WCV_3
UNION ALL
SELECT CASE WHEN #WCV_3.VISIT_2 IS NULL THEN '' ELSE CONVERT(VARCHAR(10), #WCV_3.VISIT_2,110) END AS SomeColumn FROM #WCV_3
UNION ALL
SELECT CASE WHEN #WCV_3.VISIT_4 IS NULL THEN '' ELSE CONVERT(VARCHAR(10), #WCV_3.VISIT_4, 110) END AS SomeColumn FROM #WCV_3
UNION ALL
SELECT CASE WHEN #WCV_3.VISIT_5 IS NULL THEN '' ELSE CONVERT(VARCHAR(10), #WCV_3.VISIT_5, 110) END AS SomeColumn FROM #WCV_3
) AS temp
Combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union.
更多信息可以在这里找到http://msdn.microsoft.com/en-us/library/ms180026.aspx
我已经测试了这个查询(没有#WCV_3
表)并且它有效:
SELECT SomeColumn
INTO #WCV_4
FROM (
SELECT CASE WHEN 'a' IS NULL THEN '' ELSE CONVERT(VARCHAR(10), 'a',110) END AS SomeColumn
UNION ALL
SELECT CASE WHEN 'a' IS NULL THEN '' ELSE CONVERT(VARCHAR(10), 'a',110) END AS SomeColumn
UNION ALL
SELECT CASE WHEN 'a' IS NULL THEN '' ELSE CONVERT(VARCHAR(10), 'a', 110) END AS SomeColumn
UNION ALL
SELECT CASE WHEN 'a' IS NULL THEN '' ELSE CONVERT(VARCHAR(10), 'a', 110) END AS SomeColumn
) AS temp
【讨论】:
这越来越近了,但我收到一条错误消息,提示“没有为 #WCV_4 的第 1 列指定任何列” 它工作。但是这个 unionall 查询生成的表不是我需要的表格式(WCV_4 有我已经定义的结构)这样最终输出将包括我数据中的其他列。 @darko 我将分别做 unionall 声明,看看会发生什么......谢谢你的帮助!!以上是关于将多个 CASE 语句合并为一个并 SELECT INTO 临时表的主要内容,如果未能解决你的问题,请参考以下文章