2014-01-16 99 views
0

的數據將是這樣的:迴路選擇成選擇與光標

表1的模式:表2的

+-----+--+ 
|Name |Id| 
+-----+--+ 
|Alias|1 | 
+-----+--+ 
|adam |2 | 
+-----+--+ 

架構:

+-----+--+ 
|order|id| 
+-----+--+ 
|ord1 |1 | 
+-----+--+ 
|ord2 |1 | 
+-----+--+ 
|ord3 |1 | 
+-----+--+ 
|ord4 |2 | 
+-----+--+ 
|ord5 |2 | 
+-----+--+ 

我想要的結果是這樣的:

+-----+-+ 
|Alias|1| 
+-----+-+ 
|ord1 |1| 
+-----+-+ 
|ord2 |1| 
+-----+-+ 
|ord3 |1| 
+-----+-+ 
|adam |2| 
+-----+-+ 
|ord4 |2| 
+-----+-+ 
|ord5 |2| 
+-----+-+ 

我用光標試過這個:

DECLARE @name, @id, @order 
DECLARE curs_Fp CURSOR FOR 

SELECT c.name, c.id, o.order FROM customer c INNER JOIN ORDER o ON c.id = o.id 

OPEN curs_Fp 
FETCH NEXT FROM curs_Fp INTO @name, @id, @order 

    WHILE @@FETCH_STATUS = 0 
BEGIN 

     SELECT @name, @id 

     --here I spose to do something for loopping every orders to a customer where c.id = o.id 
     SELECT @order, @id 

FETCH NEXT FROM curs_Fp INTO @name, @id, @order 
END 

CLOSE curs_Fp 
DEALLOCATE curs_Fp 

回答

0

嘗試這個..............這是工作

create table #table (name varchar(30),[order] varchar(10),id varchar(3)) 

DECLARE @name varchar(30), @id int 
DECLARE curs_Fp CURSOR FOR 

SELECT c.name, c.id FROM customer c 

OPEN curs_Fp 
FETCH NEXT FROM curs_Fp INTO @name, @id 

    WHILE @@FETCH_STATUS = 0 
BEGIN 

     insert into #table 
     SELECT @name, @id ,'' 

     insert into #table 
     SELECT '',o.[order],o.id FROM ORDER o where o.id = @id 

FETCH NEXT FROM curs_Fp INTO @name, @id 
END 

CLOSE curs_Fp 
DEALLOCATE curs_Fp 

select * from #table 
drop table #table 
0

我覺得你對遊標的工作方式有點困惑。試試這個

DECLARE @name, @id, @order 
DECLARE curs_Fp CURSOR FOR 

SELECT c.name, c.id, FROM customer c -- first i select everthing in the customer table 

OPEN curs_Fp 
FETCH NEXT FROM curs_Fp INTO @name, @id 

    WHILE @@FETCH_STATUS = 0 
     BEGIN 

     print @name; 
     SELECT order , id from order where id = @id -- Now i get the orders for the customer 
FETCH NEXT FROM curs_Fp INTO @name, @id 
END 

CLOSE curs_Fp 
DEALLOCATE curs_Fp 

你也可以用簡單的選擇來做到這一點。結果應該類似於你想要的

SELECT c.name, o.id, o.order FROM customer c INNER JOIN ORDER o ON c.id = o.id 
order by name, o.order 

讓我知道,如果他們不工作。我沒有創建你的表來測試它。