2010-02-05 46 views
11

我創建了用戶定義的函數,它將逗號分隔的字符串轉換爲表格。我執行此功能,像這樣:SQL - 遍歷表記錄

select [String] as 'ID' from dbo.ConvertStringToTable('1,2,3,4') 

從該查詢結果如下所示:

ID 
-- 
1 
2 
3 
4 

在現實中,我想通過每一個在這個表中的行進行迭代。但是,我無法弄清楚如何做到這一點。有人能告訴我一些關於如何遍歷表的行的示例SQL嗎?

+2

你使用的是Oracle,SQL服務器,MySQL和...?迭代時你想做什麼? – Andomar 2010-02-05 12:33:10

+1

你能描述一下你試圖解決的問題嗎?可以肯定的是,你不需要迭代來解決你的問題。 – 2010-02-05 12:37:46

+1

我正在使用SQL Server。我想遍歷表格。 – user255048 2010-02-05 12:46:50

回答

10

文檔中的SQL SERVER 2000年5月8日,你可以使用遊標,如下圖所示。

但是,在你走下光標路徑之前,你應該先看看與SQL Server中的遊標相關的問題。

DECLARE @id VARCHAR(10) 

DECLARE myCursor CURSOR LOCAL FAST_FORWARD FOR 
    SELECT [String] AS 'ID' 
    FROM [dbo].[ConvertStringToTable]('1,2,3,4') 
OPEN myCursor 
FETCH NEXT FROM myCursor INTO @id 
WHILE @@FETCH_STATUS = 0 BEGIN 
    PRINT @id 
    -- do your tasks here 

    FETCH NEXT FROM myCursor INTO @id 

END 

CLOSE myCursor 
DEALLOCATE myCursor 
4

如果可以避免使用遊標,通常所有您真正需要的就是加入到您創建的表中。如果您的光標正在進行更新,插入或刪除,則有99.9%的機會不需要光標。遊標應該是最後的度假勝地,而不是一種手段。遍歷記錄在數據庫中幾乎總是一個糟糕的選擇。學會思考。

爲什麼要避免遊標?因爲他們創造了性能噩夢。我通過刪除curosr將流程從24小時或更長時間更改爲不到一分鐘。

1

使用下面的函數,該函數字符串和定界符....

CREATE FUNCTION [dbo].[Udfsplitstring](@Text  VARCHAR(MAX), 
             @Delimiter VARCHAR(20) = ' ') 
-- @Strings table will contain values after separated by delimiter 
RETURNS @Strings TABLE ( 
    ID INT IDENTITY PRIMARY KEY, 
    VALUE VARCHAR(MAX)) 
AS 
    BEGIN 
     DECLARE @Index INT 

     -- Set the index to -1 prior to run index through the loop 
     SET @Index = -1 

     -- Run loop till Text becomes empty 
     WHILE (Len(@Text) > 0) 
     BEGIN 
      -- Getting the index of first delimiter 
      SET @Index = Charindex(@Delimiter, @Text) 

      -- Checking if there is no delimiter in Text 
      IF (@Index = 0) 
       AND (Len(@Text) > 0) 
       BEGIN 
        -- Inserting text which separated by delimiter  
        INSERT INTO @Strings 
         VALUES (Rtrim(Ltrim(@Text))) 

        BREAK 
       END 

      -- Checking if index found in Text then run the following script 
      IF (@Index > 1) 
       BEGIN 
        -- Inserting text after separated by delimiter  
        INSERT INTO @Strings 
         VALUES (LEFT(@Text, @Index - 1)) 

        -- Separate the inserted value from text 
        SET @Text = Rtrim(Ltrim(RIGHT(@Text, (Len(@Text) - @Index))) 
          ) 
       END 
      ELSE 
       -- Separate the inserted value from text 
       SET @Text = Rtrim(Ltrim(RIGHT(@Text, (Len(@Text) - @Index)))) 
     END 

     RETURN 
    END