如何在sql中循环while

时间:2014-01-12 09:30:34

标签: sql-server function tsql

我需要执行循环,直到@ss返回null或“ - ”的数字。所以尝试下面的代码

DECLARE @i int,@ss varchar(20)
SET @i=1;
--WHILE (@ss =null)
WHILE(@i<=3)// i need to assign i value dynamically 
BEGIN
SET @ss =(SELECT dbo.GetStringPart('-','hello-world',@i))
PRINT @ss
SET @i =@i+1
END

功能:GetStringPart

ALTER FUNCTION [dbo].[GetStringPart] (@sep varchar(1), @s varchar(512),@pos int)
RETURNS VARCHAR(200)
AS
BEGIN
DECLARE @output VARCHAR(200)
;WITH Pieces(pn, start, stop) AS (
  SELECT 1, 1, CHARINDEX(@sep, @s)
  UNION ALL
  SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
  FROM Pieces
  WHERE stop > 0
)
SELECT
  @output=SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END)
FROM Pieces
WHERE pn=@pos
RETURN @Output
END

怎么做。谢谢...

1 个答案:

答案 0 :(得分:0)

使用ISIS NOT代替=<>与NULL进行比较:

WHILE @ss IS NOT NULL

哦,为了让循环第一次进行,给@ss一个虚拟初始化器:

DECLARE @i int, @ss varchar(20) = ''