DECLARE @user TABLE(
userId BIGINT,
userName NVARCHAR(20),
positionIds VARCHAR(1000)
)
DECLARE @position TABLE (
positionId BIGINT,
positionName NVARCHAR(20)
)
SET NOCOUNT ON
INSERT INTO @user (userId,userName,positionIds) VALUES(1,'小明','1,11,12')
INSERT INTO @user (userId,userName,positionIds) VALUES(2,'小华','11,12')
INSERT INTO @user (userId,userName,positionIds) VALUES(3,'小江','1')
INSERT INTO @position (positionId,positionName) VALUES(1,'总经理')
INSERT INTO @position (positionId,positionName) VALUES(11,'董事')
INSERT INTO @position (positionId,positionName) VALUES(12,'职员')
--解法1
SELECT t.*,
STUFF((
SELECT ',' + b.positionName
FROM @user a
INNER JOIN @position b
ON CHARINDEX(','+CAST(b.positionId AS NVARCHAR)+',', ','+a.positionIds+',')
> 0
WHERE t.userId = a.userId
GROUP BY
b.positionName FOR XML PATH('')
),1,1,''
) AS postionNames
FROM @user t
--解法2
--必须用到切分函数
;WITH t AS (
SELECT u.userId,p.positionName
FROM @user AS u CROSS APPLY dbo.Fun_Split(u.positionIds,',') AS f
INNER JOIN @position AS p ON CAST(f.id AS BIGINT)=p.positionId
)
,t2 AS (
SELECT B.userId,(
STUFF(
(SELECT ', '+A.positionName FROM t A WHERE A.userId=B.userId FOR XML PATH(''))
,1,1,'')
) AS positionNames FROM t B GROUP BY B.userId
)
SELECT u.*,t2.positionNames FROM t2 INNER JOIN @user AS u ON t2.userId=u.userId
/*
userId userName positionIds postionNames
1 小明 1,11,12 董事,职员,总经理
2 小华 11,12 董事,职员
3 小江 1 总经理
*/
如何切分id串并得到name串
最新推荐文章于 2023-05-19 14:05:12 发布