2014-01-12 101 views
-2

我需要執行循環,直到@ss返回null或數字「 - 」。所以嘗試了下面的代碼如何在sql循環中執行

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 [email protected]+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 [email protected] 
RETURN @Output 
END 

怎麼辦it.thanks ...

+0

你爲什麼不從你的函數,而不是這種麪條代碼返回表? –

回答

0

使用ISIS NOT代替=<>與NULL進行比較:

WHILE @ss IS NOT NULL 

哦,讓循環會在第一時間,給@ss虛擬初始化:

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