SQL select 语句字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1851896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:40:24  来源:igfitidea点击:

SQL select statement string concatenation

sqlsql-server-2008group-by

提问by user182945

Can something like this be done with a select statement:

可以使用 select 语句完成这样的操作:

SELECT col1, concat(col2 + ' ') FROM ....
       GROUP BY col1

I know i can use count(col2) or sum(col2) for integers but is there a function for concatenating if the type is nvarchar or nchar?

我知道我可以将 count(col2) 或 sum(col2) 用于整数,但是如果类型是 nvarchar 或 nchar,是否有用于连接的函数?

回答by Russ Cam

In SQL Server, if you want to concatenate across rows, there is no built in function to do this.

在 SQL Server 中,如果要跨行连接,则没有内置函数来执行此操作。

I personally like using XML PATHas it seems to perform well, but this will work only in SQL Server 2005 onwards

我个人喜欢使用 XML PATH,因为它似乎表现良好,但这只适用于 SQL Server 2005 以上

SELECT
  STUFF(
    (
    SELECT
      ' ' + Description
    FROM dbo.Brands
    FOR XML PATH('')
    ), 1, 1, ''
  ) As concatenated_string

回答by NA.

The + operatoris used to concatenate strings in T-SQL.

+运营商用于在T-SQL连接字符串。

EDIT:

编辑:

If you wish to aggregate strings over multiple rows this might help.

如果您希望在多行上聚合字符串,这可能会有所帮助

回答by Adriaan Stander

Using Sql Server there is no built-in aggregate concatenation foncton, I know MySql has one called group_concat.

使用 Sql Server 没有内置聚合连接功能,我知道 MySql 有一个叫做 group_concat 的。

Sql Server, you, would either have to write your own scaler funcion, or a CLR function to achieve this.

Sql Server,您,要么必须编写自己的缩放器函数,要么必须编写 CLR 函数来实现这一点。

Or you can use a cursor to do this for you, with a table var to return the results. I can provide an example if you like.

或者您可以使用游标为您执行此操作,并使用表 var 返回结果。如果你愿意,我可以提供一个例子。