使用MSSQL拼接多个字段的技巧(mssql 拼接多个字段)

假设有一张Albums表,里面有AlbumId, AlbumName, ArtistId, ArtistName,这里主要介绍MSSQL在拼接多个字段时,可以应用的技巧。

#### 一、FOR XML PATH

使用FOR XML PATH可以拼接最多能拼接2个字段(column),代码如下:

“`sql

SELECT AlbumName,

STUFF(

(SELECT ‘,’+ ArtistName

FROM Albums

WHERE Albums.AlbumId = A.AlbumId

FOR XML PATH(”)),1,1,”) As Artists

FROM Albums A

GROUP BY AlbumName


#### 二、CORSS APPLY

使用CORSS APPLY可以拼接无限个字段,也就是多表关联。代码如下:

```sql
SELECT AlbumName,
AR.ArtistName
FROM Albums A
CROSS APPLY (
SELECT STUFF(
(SELECT ',' + ArtistName
FROM Albums
WHERE Albums.AlbumId = A.AlbumId
FOR XML PATH('')),1,1,'')) AR(ArtistName)
GROUP BY AlbumName, AR.ArtistName

#### 三、存储过程

如果想得到更加详细的结果,可以考虑使用存储过程。先使用一个过程把基础表拼接出来,然后再根据需求进行拼接,增加准确度。代码如下:

“`sql

CREATE PROCEDURE usp_AlbumName

AS

BEGIN

–Put the final result into variable @strSQL

DECLARE @strSQL nvarchar(max)

–Declare a table variable

DECLARE @Album TABLE (AlbumName varchar(50))

–Declare a variable

DECLARE @Artists varchar(500) = ”

–Insert data in table variable

INSERT INTO @Album SELECT AlbumName

FROM Albums

GROUP BY AlbumName

–Looping for results

WHILE EXISTS (SELECT * FROM @Album)

BEGIN

–Declare two variables for the data

DECLARE @AlbumName varchar(50)

DECLARE @isFirst BIT = 1

–Get the first row from table variable

SELECT TOP 1 @AlbumName = AlbumName FROM @Album

–Delete this row

DELETE FROM @Album

WHERE AlbumName = @AlbumName

–Looping through the table

SELECT @Artists = @Artists + CASE WHEN @isFirst = 0 THEN ‘,’ ELSE ” END + ArtistName

FROM Albums

WHERE AlbumName = @AlbumName

–Change the first flag to 0

SET @isFirst = 0

–Connect the Artist to Album

SET @strSQL = @strSQL + ‘”‘ + @AlbumName + ‘”:”‘ + @Artists + ‘”.’

END

–Remove the last character

SET @strSQL = LEFT(@strSQL,Len(@strSQL)-1)

–Execute the final result

EXEC sp_executesql @strSQL

END


以上就是MSSQL在拼接多个字段时,可以应用的技巧,选择不同的方法,可以拼接出我们想要的结果,可以根据不同的业务场景,以及所拼接数据量,来决定选择何种技巧。

数据运维技术 » 使用MSSQL拼接多个字段的技巧(mssql 拼接多个字段)