在SQL Server中,我想更新一个字符串,以便删除空格(或任何给定字符)仅,如果它出现在两个数字之间。
输入:
q 12 1 4 12422 test 1 testagain
预期产出:
q 121412422 test 1 testagain
有没有优雅的方法呢?
谢谢!
答案 0 :(得分:2)
创建此功能:
CREATE FUNCTION [dbo].[RemoveSpaceBetweenNumbers] (@str varchar(max))
RETURNS varchar(max)
BEGIN
WHILE PATINDEX('%[0-9] [0-9]%',@str) > 0
BEGIN
SET @str = STUFF(@str, PATINDEX('%[0-9] [0-9]%',@str)+1,1,'')
END;
RETURN @str;
END;
然后您可以像这样更新您的字段:
UPDATE YourTable SET YourColumn=dbo.RemoveSpaceBetweenNumbers(YourColumn);
答案 1 :(得分:1)
declare @str varchar(max)='q 12 1 4 12422 test 1 testagain'
declare @T table (item varchar(500) not null)
declare @d varchar(10)
set @d = ' '
declare @start int
declare @len int
declare @pos int
declare @pos1 int
declare @val varchar(500)
set @pos = 1
Set @start = charindex(@d,@str,@pos)
Set @len = len(@str)
While @start <= @len
begin
if (@pos = 1)
begin
set @val = substring(@str,1,@start-1)
insert into @T values(@val)
set @pos = @pos + 1
end
else
begin
Set @pos1 = charindex(@d,@str,@start+1)
if @pos1 = 0
begin
set @val = substring(@str,@start+1,@len-@start)
insert into @T values(@val)
break;
end
set @val = substring(@str,@start+1,@pos1-@start-1)
insert into @T values(@val)
set @start = @pos1
set @pos1 = 0
end
end
DECLARE @OUTPUT VARCHAR(MAX), @previtem varchar(500), @item varchar(500)
DECLARE CRS CURSOR FOR
SELECT item FROM @T
OPEN CRS
FETCH NEXT FROM CRS INTO @previtem
SET @OUTPUT=@previtem
WHILE (@@fetch_status = 0)
BEGIN
FETCH NEXT FROM CRS INTO @item
IF (@item<>@previtem)
BEGIN
IF (ISNUMERIC(@item)=1 AND ISNUMERIC(@previtem)=1)
SET @OUTPUT = @OUTPUT + @item
ELSE
SET @OUTPUT = @OUTPUT + ' ' + @item
END
SET @previtem=@item
END
CLOSE CRS
DEALLOCATE CRS
select @OUTPUT
select * from @T
答案 2 :(得分:0)
我会:
我会在我的应用程序而不是T-SQL中执行此操作。这将更容易,更简单,更短的路径。