T-Sql 实现类似访问数组变量的操作
????? 目前T-SQL不支持Array這種類型,大多數(shù)情況我們需要用游標(biāo)來(lái)實(shí)現(xiàn)。除了游標(biāo)后我們還可以用臨時(shí)表,這里我們演示使用表變量來(lái)實(shí)現(xiàn),直接看下來(lái)的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先創(chuàng)建一個(gè)表變量,然后插入初始數(shù)據(jù),這些數(shù)據(jù)可能是你需要處理的數(shù)據(jù)。然后有一個(gè)設(shè)有一個(gè)標(biāo)志列標(biāo)記當(dāng)前行有沒(méi)有執(zhí)行過(guò)。你可以根據(jù)上面的代碼模板修改成為你自己的。
希望對(duì)您開(kāi)發(fā)有幫助。
您可以感興趣的文章:
T-SQL使用DbMail發(fā)送多個(gè)附件
在T-SQL中使用正則表達(dá)式函數(shù)
SQLSERVER2008使用CTE轉(zhuǎn)換string到Table
SqlServer中使用T-sql找出identity列
?
作者:Petter Liu
出處:http://www.cnblogs.com/wintersun/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁(yè)面明顯位置給出原文連接,否則保留追究法律責(zé)任的權(quán)利。
該文章也同時(shí)發(fā)布在我的獨(dú)立博客中-Petter Liu Blog。
轉(zhuǎn)載于:https://www.cnblogs.com/wintersun/archive/2012/06/15/2550349.html
總結(jié)
以上是生活随笔為你收集整理的T-Sql 实现类似访问数组变量的操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: VC菜菜鸟:基于CFree的HelloW
- 下一篇: Algorithm Course Rev