簡體   English   中英

遍歷 SQL Server 2008 中的行

[英]Iterate through rows in SQL Server 2008

考慮表 SAMPLE:

id       integer
name     nvarchar(10)

有一個名為myproc的存儲過程。 它只需要一個參數(即 id)

給定一個名稱作為參數,找到name = @nameparameter的所有行並將所有這些 id 傳遞給myproc

例如:

sample->
1   mark
2   mark
3   stu
41  mark

mark通過時, 1,2 and 41將分別傳遞給myproc

即應該發生以下情況:

execute myproc 1
execute myproc 2
execute myproc 41

我無法觸摸myproc也無法查看其內容。 我只需要將值傳遞給它。

如果您必須迭代(*),請使用設計用於執行此操作的構造 - cursor 備受詬病,但如果它最清楚地表達了你的意圖,我說使用它:

DECLARE @ID int
DECLARE IDs CURSOR LOCAL FOR select ID from SAMPLE where Name = @NameParameter

OPEN IDs
FETCH NEXT FROM IDs into @ID
WHILE @@FETCH_STATUS = 0
BEGIN
    exec myproc @ID

    FETCH NEXT FROM IDs into @ID
END

CLOSE IDs
DEALLOCATE IDs

(*)這個答案最近收到了一些贊成票,但我覺得我應該在這里也加入我的原始評論,並添加一些一般性建議:

在 SQL 中,您通常應該尋求基於集合的解決方案。 整個語言都圍繞基於集合的解決方案,並且(反過來)優化器旨在使基於集合的解決方案運行良好。 進而,我們可用於調整優化器的工具也是面向集合的——例如將索引應用於表。

某些情況下,迭代是最好的方法。 這些是相距甚遠的,並且可能類似於傑克遜的優化規則 - 不要這樣做 - 並且(僅限專家)要這樣做。

您最好首先嘗試根據要影響的所有行的集合來制定您想要的內容 - 要實現的總體變化是什么? - 然后嘗試制定一個封裝該目標的查詢。 只有當這樣做產生的查詢沒有充分執行(或者有一些其他組件除了單獨處理每一行之外無法做任何事情)時,您才應該考慮迭代。

我只是聲明臨時表 @sample 並插入所有具有 name='rahul' 的行,並使用狀態列檢查該行是否已迭代。並使用 while 循環我遍歷臨時表 @sample 的所有行具有 name='rahul' 的所有 id

use dumme

Declare @Name nvarchar(50)
set @Name='Rahul'
DECLARE @sample table (

    ID int,
    Status varchar(500)

    )
insert into @sample (ID,status) select ID,0 from sample where sample=@name
while ((select count(Id) from @sample where status=0 )>0) 
begin
    select top 1  Id  from @sample where status=0 order by Id
    update @sample set status=1  where Id=(select top 1  Id  from @sample where status=0 order by Id) 
end
Declare @retStr varchar(100)

select @retStr = COALESCE(@retStr, '') + sample.ID + ', '
from sample 
WHERE sample.Name = @nameparameter 
select  @retStr = ltrim(rtrim(substring(@retStr , 1, len(@retStr )- 1)))

Return  ISNULL(@retStr ,'') 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM