Hi @Will Faulkner ,
For versions of SQL Server 2017 and later, the easiest way to merge strings is to use the function STRING_AGG (this function was introduced in SQL Server 2017), and for versions before SQL Server 2017, we generally use xml path or user-defined functions to merge strings.
The method of xml path has been provided by Viorel, the following is the method of using user-defined functions, please also check:
CREATE TABLE yourtable(REF int,Field1 varchar(15),Field2 varchar(15))
INSERT INTO yourtable VALUES(1,'a','x'),(1,'b','y'),(1,'c','z')
CREATE FUNCTION fn_hb1(@REF VARCHAR(100))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @Rst VARCHAR(8000)
SET @Rst=''
SELECT @Rst=@Rst+Field1+',' FROM yourtable WHERE REF=@REF
SET @Rst=Left(@Rst,LEN(@RSt)-1)
RETURN @Rst
END
GO
CREATE FUNCTION fn_hb2(@REF VARCHAR(100))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @Rst VARCHAR(8000)
SET @Rst=''
SELECT @Rst=@Rst+Field2+',' FROM yourtable WHERE REF=@REF
SET @Rst=Left(@Rst,LEN(@RSt)-1)
RETURN @Rst
END
GO
SELECT * FROM yourtable
SELECT REF,dbo.fn_hb1(REF) AS Field1,dbo.fn_hb2(REF) AS Field2
FROM yourtable
GROUP BY REF;
DROP TABLE yourtable
DROP FUNCTION fn_hb1
DROP FUNCTION fn_hb2
Output:
If you have any question, please feel free to let me know.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.