2011-09-01 64 views
1

請大家幫忙。下面的查詢不按預期工作。預計在@ count = 1時停止插入,但不會停止。我無法弄清楚問題所在,請幫助我。迭代循環內光標不按預期方式工作

create procedure mypro 
as 

declare @count int 
declare aa cursor 

for select SerialNumb from FORMTABLE 

    open aa 

     declare @SerialNumb varchar(11) 
     fetch next from aa into @SerialNumb 

     while(@@FETCH_STATUS<>-1) 
     begin 
      if(@@FETCH_STATUS <>-2) 
      select @count= COUNT(SerialNumb) from CARDTABLE where [email protected] 
      while (@count<>1) 
      begin 

    ---- variables declaration 

      declare @name 
      declare @location 
      declare @status 


     select @name = name, @location = location, @status=status 

     from FORMTABLE where SerialNumb = @SerialNumb 


     insert into FORMTABLE values(@name, @location, @status) 


     set @count = @count-1 
     end 
     fetch next from aa into @SerialNumb 
      end 

close aa 

deallocate aa 

參見樣本數據如下:

DECLARE @FormTable TABLE 
(
Serialnumb INT, 
[GROUP] CHAR(1), 
CLASS VARCHAR(50) 
) 

INSERT INTO @FormTable 
SELECT 400,'A','Science' UNION ALL 
SELECT 401,'B','Social science' UNION ALL 
SELECT 402,'C','philosophy' UNION ALL 
SELECT 403,'D','Engineering' 

CardTable

DECLARE @CardTable TABLE 
(
Id INT PRIMARY KEY, 
Serialnumb INT, 
Name VARCHAR(50) 
) 

INSERT INTO @CardTable 
SELECT 1,400,'Charey' UNION ALL 
SELECT 2,400,'Mike' UNION ALL 
SELECT 3,400,'James' UNION ALL 
SELECT 4,401,'Vina' UNION ALL 
SELECT 5,400,'Gloria' UNION ALL 
SELECT 6,401,'Faith' UNION ALL 
SELECT 7,401,'Sarah' UNION ALL 
SELECT 8,402,'Joy' UNION ALL 
SELECT 9,402,'Rita' 

期望的結果應該是:

@FormTable

Serialno Group  Class 
400  A  Science 
401  B  Social science 
402  C  philosophy 
403  D  Engineering 
400  A  Science 
400  A  Science 
400  A  Science 
401  B  Social science 
401  B  Social science 
402  C  philosophy 
+1

乍一看,這看起來像你可能不需要光標的東西。你能描述它打算做什麼嗎? –

+0

@Martin,它意味着來自CARDTABLE的COUNT(SerialNumb),而@count <> 1,插入到FORMTABLE中,但它一直重複插入。 – jenni

+1

我看到你已經爲2個表添加了一些示例數據。現在你的光標試圖根據這些數據來做什麼? –

回答

0

我的確同意Martin的看法,你似乎根本不需要光標。簡單的加入就足夠了。

爲什麼要再次將數據存儲在Form Table中?

+0

我希望兩個表中每個serialnumb的計數相同@Nil – jenni

+0

您可以嘗試Martin提供的查詢,我認爲這就是您所需要的。 –