目前我已经到了
SELECT
DESCRIPTION,
LEFT(DESCRIPTION,
CASE
WHEN CHARINDEX(',', DESCRIPTION) = 0 THEN LEN(DESCRIPTION)
ELSE charindex(',', DESCRIPTION) - 1
END) AS LEFTDESCRIPTION,
RIGHT(DESCRIPTION,
CASE
WHEN CHARINDEX(',',REVERSE(DESCRIPTION)) = 0 THEN ''
ELSE charindex(',', DESCRIPTION) - 1
END) AS RIGHTDESCRIPTION
FROM TABLE
但是RIGHT部分似乎不正确,例如:
它得到了一个例子的描述,并且返回“ample,this”而不仅仅是“this”
答案 0 :(得分:4)
由于您知道如何获取逗号的内容LEFT
,因此可以在REVERSE
'd值上使用相同的操作逻辑来获取RIGHT
的{{1}}原始字符串,
DECLARE @Var VARCHAR(50) = 'example,this'
SELECT @Var
, LEFT(@Var, CHARINDEX(',', @Var) - 1) -- returns 'example'
, REVERSE(LEFT(REVERSE(@Var), CHARINDEX(',', REVERSE(@Var)) - 1)) -- returns 'this'
-- or when using the RIGHT function,
, RIGHT(@Var, LEN(@Var) - CHARINDEX(',', @Var)) -- returns 'this'
Per Juan的评论,下面是与上面相同的SELECT
(这次选择RIGHT
路由而不是REVERSE
逻辑),当找不到逗号分隔符时将返回该值,
DECLARE @Var VARCHAR(100) = 'example,this'
SELECT @Var
, CASE WHEN @Var LIKE '%,%' THEN LEFT(@Var, CHARINDEX(',', @Var) - 1)
ELSE @Var END
, CASE WHEN @Var LIKE '%,%' THEN RIGHT(@Var, LEN(@Var) - CHARINDEX(',', @Var))
ELSE @Var END
答案 1 :(得分:1)
我倾向于使用stuff()
:
select description,
left(description, charindex(',', description) - 1) as leftdescription,
stuff(description, 1, charindex(',', description), '') as rightdescription
如果您担心,
不在场,请使用case
:
select description,
(case when description like '%,%'
then left(description, charindex(',', description) - 1)
else description
end) as leftdescription,
(case when description like '%,%'
then stuff(description, 1, charindex(',', description), '')
end) as rightdescription
答案 2 :(得分:1)
这样做。你非常接近。
SELECT
DESCRIPTION,
LEFT(DESCRIPTION,
CASE
WHEN CHARINDEX(',', DESCRIPTION) = 0 THEN LEN(DESCRIPTION)
ELSE charindex(',', DESCRIPTION) - 1
END) AS LEFTDESCRIPTION,
REVERSE(LEFT(Reverse(DESCRIPTION),
CASE
WHEN CHARINDEX(',',REVERSE(DESCRIPTION)) = 0 THEN ''
ELSE charindex(',', REVERSE(DESCRIPTION)) - 1
END)) AS RIGHTDESCRIPTION
FROM TABLE
答案 3 :(得分:0)
DECLARE @Var VARCHAR(50) = 'example,this'
SELECT LEFT(@Var, COALESCE(NULLIF(CHARINDEX(',', @Var) - 1, -1), LEN(@Var))) LEFTDESCRIPTION,
REPLACE(@Var, LEFT(@Var, COALESCE(NULLIF(CHARINDEX(',', @Var), 0), LEN(@Var))), '') RIGHTDESCRIPTION