SQL Server:连接多列的最佳方式? [英] SQL Server: Best way to concatenate multiple columns?
问题描述
我正在尝试在 SQL Server 11.00.3393 的查询中连接多个列.
I am trying to concatenate multiple columns in a query in SQL Server 11.00.3393.
我尝试了新函数 CONCAT()
但当我使用两列以上时它不起作用.
I tried the new function CONCAT()
but it's not working when I use more than two columns.
所以我想知道这是否是解决问题的最佳方法:
So I wonder if that's the best way to solve the problem:
SELECT CONCAT(CONCAT(CONCAT(COLUMN1,COLUMN2),COLUMN3),COLUMN4) FROM myTable
由于 NULL
值,我无法使用 COLUMN1 + COLUMN2
.
I can't use COLUMN1 + COLUMN2
because of NULL
values.
编辑
如果我尝试 SELECT CONCAT('1','2','3') AS RESULT
我得到一个错误
If I try SELECT CONCAT('1','2','3') AS RESULT
I get an error
CONCAT 函数需要 2 个参数
The CONCAT function requires 2 argument(s)
推荐答案
通过讨论很明显问题在于使用 VS2010 编写查询,因为它使用规范的 CONCAT()
函数仅限于 2 个参数.可能有一种方法可以改变这种情况,但我不知道.
Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT()
function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.
另一种选择:
SELECT '1'+'2'+'3'
这种方法需要将非字符串值强制转换/转换为字符串,以及通过 ISNULL()
或 COALESCE()
处理 NULL
代码>:
This approach requires non-string values to be cast/converted to strings, as well as NULL
handling via ISNULL()
or COALESCE()
:
SELECT ISNULL(CAST(Col1 AS VARCHAR(50)),'')
+ COALESCE(CONVERT(VARCHAR(50),Col2),'')
这篇关于SQL Server:连接多列的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!