循环选择用光标选择

时间:2014-01-16 07:53:58

标签: sql sql-server sql-server-2008 tsql cursor

数据将是这样的:

表1的模式:

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

表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

2 个答案:

答案 0 :(得分: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 

如果他们不工作,请告诉我。我没有创建你的表来测试它。

答案 1 :(得分: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