我正在尝试更改以下格式的字符串:

"12_7,34_22,28_4,6_22"




"12,34,28,6"


本质上,我想从字符串中消除“ _”(下划线以及在逗号之后的所有内容)。尚未使用sql,因此对我来说,这似乎是一项艰巨的任务。

最佳答案

CREATE FUNCTION DeUnderscore(@s nvarchar(max))
RETURNS nvarchar(max)
AS
BEGIN
    DECLARE @iu int = CHARINDEX('_', @s); -- position of _
    DECLARE @ic int = CHARINDEX(',', @s, @iu) -- position of ,
    WHILE (@iu != 0)
    BEGIN
        IF @ic = 0 SET @ic = LEN(@s) + 1; -- if there's no , go to end of string
        SET @s = STUFF(@s, @iu, @ic - @iu, ''); -- replace everything after _ and before , with ''
        SET @iu = CHARINDEX('_', @s);
        SET @ic = CHARINDEX(',', @s, @iu)
    END
    RETURN @s
END


..在使用中它看起来像..

SELECT dbo.DeUnderscore(myValue) AS myCleanedValue FROM myTable;

10-08 04:41