本文介紹了T-SQL:循環(huán)遍歷已知值數(shù)組的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
這是我的場(chǎng)景:
假設(shè)我有一個(gè)存儲(chǔ)過(guò)程,我需要在其中對(duì)一組特定的 id 調(diào)用另一個(gè)存儲(chǔ)過(guò)程;有沒(méi)有辦法做到這一點(diǎn)?
Let's say I have a stored procedure in which I need to call another stored procedure on a set of specific ids; is there a way to do this?
即而不是需要這樣做:
exec p_MyInnerProcedure 4
exec p_MyInnerProcedure 7
exec p_MyInnerProcedure 12
exec p_MyInnerProcedure 22
exec p_MyInnerProcedure 19
做這樣的事情:
*magic where I specify my list contains 4,7,12,22,19*
DECLARE my_cursor CURSOR FAST_FORWARD FOR
*magic select*
OPEN my_cursor
FETCH NEXT FROM my_cursor INTO @MyId
WHILE @@FETCH_STATUS = 0
BEGIN
exec p_MyInnerProcedure @MyId
FETCH NEXT FROM my_cursor INTO @MyId
END
我在這里的主要目標(biāo)只是可維護(hù)性(隨著業(yè)務(wù)的變化易于刪除/添加 ID),能夠在一行中列出所有 ID...性能不應(yīng)該是一個(gè)大問(wèn)題
My Main goal here is simply maintainability (easy to remove/add id's as the business changes), being able to list out all Id's on a single line... Performance shouldn't be as big of an issue
推薦答案
declare @ids table(idx int identity(1,1), id int)
insert into @ids (id)
select 4 union
select 7 union
select 12 union
select 22 union
select 19
declare @i int
declare @cnt int
select @i = min(idx) - 1, @cnt = max(idx) from @ids
while @i < @cnt
begin
select @i = @i + 1
declare @id = select id from @ids where idx = @i
exec p_MyInnerProcedure @id
end
這篇關(guān)于T-SQL:循環(huán)遍歷已知值數(shù)組的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!