我知道遊標被人們所詬病,我儘量避免使用它們,但可能有一些合理的理由來使用它們。我有一個,我正在嘗試使用一對遊標:一個用於主表,另一個用於輔助表。主表遊標遍歷外循環中的主表。輔助表格光標遍歷內部循環中的輔助表格。 問題是,主表遊標顯然正在進行並將主鍵列值[Fname]保存到本地變量@Fname中,但它沒有獲取輔助表中相應外鍵列的行。對於輔助表,它始終返回其外鍵列值與主表的第一行的主鍵列值相匹配的行。T-Sql光標不能繼續提取
以下是我想要在真實存儲過程中執行的一個非常簡單的示例。 名是主表
SET NOCOUNT ON
DECLARE
@Fname varchar(50) -- to hold the fname column value from outer cursor loop
,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop
,@score int
;
--prepare primary table to be iterated in the outer loop
DECLARE @Names AS Table (Fname varchar(50))
INSERT @Names
SELECT 'Jim' UNION
SELECT 'Bob' UNION
SELECT 'Sam' UNION
SELECT 'Jo'
--prepare secondary/detail table to be iterated in the inner loop
DECLARE @Scores AS Table (Fname varchar(50), Score int)
INSERT @Scores
SELECT 'Jo',1 UNION
SELECT 'Jo',5 UNION
SELECT 'Jim',4 UNION
SELECT 'Bob',10 UNION
SELECT 'Bob',15
--cursor to iterate on the primary table in the outer loop
DECLARE curNames CURSOR
FOR SELECT Fname FROM @Names
OPEN curNames
FETCH NEXT FROM curNames INTO @Fname
--cursor to iterate on the secondary table in the inner loop
DECLARE curScores CURSOR
FOR
SELECT FName,Score
FROM @Scores
WHERE Fname = @Fname
--*** NOTE: Using the primary table's column value @Fname from the outer loop
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Outer loop @Fname = ' + @Fname
OPEN curScores
FETCH NEXT FROM curScores INTO @FK_Fname, @Score
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score)
FETCH NEXT FROM curScores INTO @FK_Fname, @Score
END
CLOSE curScores
FETCH NEXT FROM curNames INTO @Fname
END
DEALLOCATE curScores
CLOSE curNames
DEALLOCATE curNames
下面是我得到的結果。請注意,對於外部循環,它會顯示最新的Fname,但是當Fname用作@Fname從輔助表中獲取相關行以進行後續迭代時,它仍會獲得與第一個匹配的行行(Bob)的主表。
Outer loop @Fname = Bob
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
Outer loop @Fname = Jim
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
Outer loop @Fname = Jo
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
Outer loop @Fname = Sam
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
請讓我知道我做錯了什麼。 在此先感謝!
謝謝奧維迪烏。那就是訣竅! – Aamir 2008-10-28 19:46:25