0

我正在尝试更改格式为 say 的字符串:

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

"12,34,28,6"

本质上,我想从字符串中删除“_”(下划线以及之后和之前的任何内容)。没有使用过 sql,所以对我来说它看起来像是一项艰巨的任务。

4

4 回答 4

1
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;
于 2012-07-20T19:18:21.807 回答
0

你可能想看看在 MySQL 中定义你自己的函数。这将允许您在函数内写出一组命令,这些命令可以利用 DB 固有的字符串操作函数并输出所需的结果。例如,您可以定义一个类似 myStringFunction 的函数,并在该函数中找到所有下划线和逗号的索引位置,然后提取所需的子字符串并再次将它们连接在一起。您在查询中的使用可能会像这样。

从表中选择 myStringFunction(field_name);

于 2012-07-20T18:40:32.543 回答
0

试试这个:

DECLARE @str varchar(100)='12_7,34_22,28_4,6_22'
DECLARE @out varchar(100)=''
While(CHARINDEX('_',@str,1) > 0)
begin
SET @out=@out+LEFT(REPLACE(@str,SUBSTRING(@str,CHARINDEX('_',@str,1),CHARINDEX(',',@str,1)-CHARINDEX('_',@str,1)),''),CHARINDEX(',',REPLACE(@str,SUBSTRING(@str,CHARINDEX('_',@str,1),CHARINDEX(',',@str,1)-CHARINDEX('_',@str,1)),'')))
SET @str=RIGHT(REPLACE(@str,SUBSTRING(@str,CHARINDEX('_',@str,1),CHARINDEX(',',@str,1)-CHARINDEX('_',@str,1)),''),LEN(REPLACE(@str,SUBSTRING(@str,CHARINDEX('_',@str,1),CHARINDEX(',',@str,1)-CHARINDEX('_',@str,1)),''))-CHARINDEX(',',REPLACE(@str,SUBSTRING(@str,CHARINDEX('_',@str,1),CHARINDEX(',',@str,1)-CHARINDEX('_',@str,1)),'')))

end
select @out+@str
于 2012-07-25T07:39:59.923 回答
0

在没有while循环的情况下尝试这个解决方案

declare @str varchar(30)='12_7,34_22,28_4,6_22,8_545'

;with cte (startPos,strg) as(
 select CHARINDEX('_',@str,1) [startPos],cast(@str as varchar(500)) as [strg]
 union all
 select CHARINDEX('_',[strg],[startPos])+1 [startPos],cast(stuff([strg],
 CHARINDEX('_',[strg],[startPos]),CHARINDEX(',',[strg],
 [startPos])-CHARINDEX('_',[strg],[startPos]),'') as varchar(500)) as [strg] 
 from cte
 where  CHARINDEX('_',[strg],[startPos])>0
)
select substring(MIN(strg),1,CHARINDEX('_',MIN(strg),1)-1) from cte
于 2012-07-25T11:20:52.087 回答