Fis*_*ead 5 sql-server sql-server-2008-r2
我有三个语句要组合,但我找不到 SQL Server 2008 R2 的正确解决方案:
我需要将三列连接为一列,但根据最后一列的结果以三种不同的方式连接。第 3 列可以是空值、字母数字字母或以“-”开头,后跟数字。我尝试了以下方法:
if (select * from col3 where col3 is null)
select col1 + ' ' + col2
else if (select * from col3 where col3 like '-%'
select col1 + ' ' + col2 + col3
else if (select * from col3 where col3 not like '-%'
select col1 + ' ' + col2 + ' ' + col3
Run Code Online (Sandbox Code Playgroud)
分别地,它们像魅力一样工作。当尝试像上面的语句那样组合它们时,它们向我抛出一个错误,说我创建了一个布尔值而不是预期的条件。
我如何表述这是正确的?
Ken*_*her 16
您正在寻找的语法是 case 语句。您可以使用IF .. EXISTS
来控制代码中的流程,但对于这样的事情,该CASE WHEN
语句就是您想要的。
SELECT CASE WHEN col3 IS NULL THEN col1 + ' ' + col2
WHEN col3 LIKE '-%' THEN col1 + ' ' + col2 + col3
WHEN col3 NOT LIKE '-%' THEN col1 + ' ' + col2 + ' ' + col3
END AS ConcatCol
FROM TableName;
Run Code Online (Sandbox Code Playgroud)
并简化为:
SELECT col1 + ' ' + col2
+ CASE WHEN col3 IS NULL THEN ''
WHEN col3 LIKE '-%' THEN col3
ELSE ' ' + col3
END AS ConcatCol
FROM TableName;
Run Code Online (Sandbox Code Playgroud)
假设我当然明白你想要做什么。
编辑:为列添加别名
小智 0
如果我回答你的问题是正确的:
if exists (select 1 from col3 where col3 is null)
select col1 + ' ' + col2 from ... where ...
else if exists (select 1 from col3 where col3 like '-%')
select col1 + ' ' + col2 + col3 from ... where ...
else if exists(select 1 from col3 where col3 not like '-%')
select col1 + ' ' + col2 + ' ' + col3 from ... where ...
Run Code Online (Sandbox Code Playgroud)