我想遍历值并一次从值中删除1个字符并显示结果。
因此,如果我有一个带有值的表:
ID
___
34679
13390
89906
我希望结果看起来像这样
Id
----
4679
679
79
9
3390
390
90
0
9906
906
06
6
我想遍历值并一次从值中删除1个字符并显示结果。
因此,如果我有一个带有值的表:
ID
___
34679
13390
89906
我希望结果看起来像这样
Id
----
4679
679
79
9
3390
390
90
0
9906
906
06
6
Answers:
请不要对这样的事情使用循环(我也将递归CTE保留给您对事物(例如层次结构)的控制要少得多的场景。循环在SQL中是不好的。SQL已优化为可按集合工作。
DECLARE @foo TABLE(ID INT);
INSERT @foo VALUES(34679),(13390),(89906);
;WITH x AS
(
SELECT TOP (2048) n = ROW_NUMBER() OVER (ORDER BY Number)
FROM master.dbo.spt_values ORDER BY Number
)
SELECT RIGHT(f.ID, x.n) FROM x
INNER JOIN @foo AS f
ON x.n < LEN(f.ID);
结果:
9
79
679
4679
0
90
390
3390
6
06
906
9906
declare @MyString varchar(500)
set MyString = '1,2.3#45.#,.6'
select dbo.RemoveChars(MyString, '#,.')
create function [dbo].[RemoveChars] (
@InputString varchar(MAX)
,@CharsToRemove varchar(500)
)
returns varchar(MAX)
as
begin
declare @len int
,@Counter int
,@OneChar char(1)
set @Counter = 1
set @len = LEN(@CharsToRemove);
while (1 = 1)
begin
set @OneChar = SUBSTRING(@CharsToRemove, @Counter, 1)
set @InputString = REPLACE(@InputString, @OneChar, '')
set @Counter = @Counter + 1
if (
@Counter > @len
or @Counter > 20
)
break;
end
return @InputString
end
CREATE PROC udploop (@num varchar(10))
AS
BEGIN
DECLARE @len int;
SET @len = LEN(@num);
WHILE (@len > 1)
BEGIN
SELECT
@num = RIGHT(@num, @len - 1);
PRINT @num;
SET @len = LEN(@num);
END
END
执行:
EXEC udploop 34679
EXEC udploop 13390
EXEC udploop 89906
结果:
4679
679
79
9
3390
390
90
0
9906
906
06
6