T-Sql 實現類似訪問數組變量的操作


      目前T-SQL不支持Array這種類型,大多數情況我們需要用游標來實現。除了游標后我們還可以用臨時表,這里我們演示使用表變量來實現,直接看下來的T-SQL:

 

--Then "iterate" through it executing the necessary SQL from those values.
--This will allow you to have 0 to MANY values to be executed, so you don't have to set up a variable for each.
--The following is a complete sample of how you may go about doing that without cursors.
 
SET NOCOUNT ON
DECLARE @dict TABLE (
                    id          INT IDENTITY(1,1), -- a unique identity column for reference later
                    value       VARCHAR(50),       -- your parameter value to be passed into the procedure
                    executed    BIT                -- BIT to mark a record as being executed later
                    )
 
-- INSERT YOUR VALUES INTO @dict HERE
-- Set executed to 0 (so that the executio    n process will pick it up later)
-- This may be a SELECT statement into another table in your database to load the values into @dict
INSERT @dict
SELECT '390adbc5-3494-4651-95af-608b69a304c1',0  UNION ALL
SELECT 'ddf23828-fbf9-4d16-81fa-3f4b465539a3',0     UNION ALL
SELECT '02627340-22cd-4758-807d-6251acd5a0e5',0    
     
DECLARE @currentid INT
DECLARE @currentvalue VARCHAR(50)
WHILE EXISTS(SELECT * FROM @dict WHERE executed = 0)
BEGIN
    -- Get the next record to execute
    SELECT 
    TOP 1   @currentid = id 
    FROM    @dict 
    WHERE   executed = 0
 
    -- Get the parameter value
    SELECT  @currentvalue = value
    FROM    @dict
    WHERE   id = @currentid
 
    -- EXECUTE THE SQL HERE 
    ---BEGIN
    PRINT   'SecondSP ' +  '@myParam int ' + '@myParam = ' + @currentvalue
    -- END
    
    -- Mark record as having been executed
    UPDATE  d
    SET     executed = 1
    FROM    @dict d
    WHERE   id = @currentid
 
END

 

上面的T-SQL先創建一個表變量,然后插入初始數據,這些數據可能是你需要處理的數據。然后有一個設有一個標志列標記當前行有沒有執行過。你可以根據上面的代碼模板修改成為你自己的。

希望對您開發有幫助。

您可以感興趣的文章:

T-SQL使用DbMail發送多個附件

在T-SQL中使用正則表達式函數

SQLSERVER2008使用CTE轉換string到Table

SqlServer中使用T-sql找出identity列

 


作者:Petter Liu
出處:http://www.cnblogs.com/wintersun/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
該文章也同時發布在我的獨立博客中-Petter Liu Blog


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM