如何切分id串并得到name串

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			总经理
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值