一,如何将select后得出的多条记录的某个字段,拼接成字符串
CREATE TABLE TB ([UserID] INT, [LastName] VARCHAR(2), [FirstName] VARCHAR(2), [UserName] VARCHAR(2))
INSERT TB
SELECT 1, 'A', 'B', 'C' UNION ALL
SELECT 2, 'A1', 'B1', 'C1' UNION ALL
SELECT 3, 'A2', 'B2', 'C2'
DECLARE @STR NVARCHAR(max)
SELECT @STR=''--一定要赋初值,否则只返回NULL
SELECT @STR=ISNULL(@STR+',','')+USERNAME FROM TB
SELECT strUserName=@STR
/*
strUserName
-----------
C,C1,C2
*/