我想用对应的值替换ID
示例:如果列包含ID 1,2,
我需要将1替换为“产品视频”,将2替换为“安装”。
我可以使用用例,但找不到用逗号分隔ID的用例的方法
SELECT BusinessFocus
,(
SELECT stuff((
SELECT ', ' + BusinessFocus
,CASE
WHEN BusinessFocus = 1
THEN 'Product Videos'
WHEN BusinessFocus = 2
THEN 'Installation Videos'
WHEN BusinessFocus = 3
THEN 'Other Videos'
END AS BFocusname
WHERE BusinessFocus IN (
SELECT val
FROM dbo.split(PartnerMaster.BusinessFocus, ',')
)
FOR XML PATH('')
), 1, 1, '')
) AS BusinessFocusNames
FROM PartnerMaster
实际结果:
预期结果:
1,3 | Product Videos,Installation Videos
答案 0 :(得分:1)
如果您只是想将“ 1,3”转换为“产品视频,其他视频”,则可以按以下方式使用REPLACE-
DECLARE @BusinessFocus VARCHAR(200) = '1,3'
SELECT @BusinessFocus,
REPLACE(REPLACE(@BusinessFocus,'1','Product Videos'),'3','Other Videos')
注意:您可以再使用一个REPLACE,如图所示。
答案 1 :(得分:1)
如果您没有将这些业务重点值存储在表中的其他位置,请使用CTE。
模式:
CREATE TABLE #PartnerMaster (BusinessFocus VARCHAR(100), BusinessFocusNames VARCHAR(MAX))
INSERT INTO #PartnerMaster (BusinessFocus)
SELECT '1,2' UNION ALL SELECT '3' UNION ALL SELECT '2,3'
现在加入Charindex
,并用For XML Path
使其用逗号分隔。
;WITH CTE AS(
SELECT '1' BusinessFocus, 'Product Videos' BusinessFocusNames
UNION ALL
SELECT '2' BusinessFocus, 'Installation Videos' BusinessFocusNames
UNION ALL
SELECT '3' BusinessFocus, 'Other Videos' BusinessFocusNames
)
SELECT P.BusinessFocus
, STUFF((SELECT ','+C.BusinessFocusNames FROM CTE C
WHERE CHARINDEX(C.BusinessFocus,P.BusinessFocus)>0
FOR XML PATH('')),1,1,'') AS BusinessFocusNames
FROM #PartnerMaster P
结果:
+---------------+------------------------------------+
| BusinessFocus | BusinessFocusNames |
+---------------+------------------------------------+
| 1,2 | Product Videos,Installation Videos |
| 3 | Other Videos |
| 2,3 | Installation Videos,Other Videos |
+---------------+------------------------------------+