• oracle使用游标进行循环数据插入


    建表语句:

    begin
    execute immediate ' drop table Customer';
    exception when others then
    null;
    end;
     

    begin
    execute immediate ' drop table OrderHistory';
    exception when others then
    null;
    end;
      

      -- Create Customer Table
    CREATE TABLE Customers
    (   
        Customer_Id NUMBER(16) NOT NULL,
        Name VARCHAR(25),
        CONSTRAINT cus_id_pk PRIMARY KEY(Customer_Id )
    )



    -- Create Order Table
    CREATE TABLE Orders
    (   
        Order_Id  NUMBER(16) NOT NULL,
        Name VARCHAR(25),
        Customer_Id NUMBER(16) NOT NULL,
        CONSTRAINT ord_id_pk PRIMARY KEY(Order_Id ),
        CONSTRAINT cus_id_fk FOREIGN KEY (Customer_Id) REFERENCES Customers(Customer_Id)
    )

     

     

    -- Create Order History Table

    begin
    execute immediate ' drop table OrderHistory';
    exception when others then
    null;
    end;

    CREATE TABLE OrderHistory
    (
        OrderHistory_Id NUMBER(16),
        CustomerName VARCHAR(25),
        OrderName VARCHAR(25),
        CONSTRAINT OrderHistory_Id_pk PRIMARY KEY(OrderHistory_Id )
    )

    插入数据的存储过程:

    CREATE PROCEDURE spAddOrderHistory
    (
        
    @CustomerName VARCHAR(25),
        
    @OrderName VARCHAR(25)
    )
    AS
    BEGIN
        
    INSERT INTO OrderHistory(CustomerName,OrderName)
        
    VALUES(@CustomerName@OrderName)
    END

    使用游标进行数据插入:

    -- use cursor to insert data into order history table
    DECLARE @customer_name VARCHAR(25)
    DECLARE @order_name VARCHAR(25)

    DECLARE curOrder CURSOR READ_ONLY
    FOR
    SELECT c.Name as [Customer Name], o.Name as [Order Name]
    FROM Customers c INNER JOIN Orders o
        
    ON c.CustomerId = o.Customer_Id
    ORDER BY [Customer Name][Order Name]

    OPEN curOrder

    FETCH NEXT FROM curOrder
    INTO @customer_name@order_name

    WHILE @@FETCH_STATUS = 0    
    BEGIN
        
    EXEC spAddOrderHistory @customer_name@order_name 
               
        
    FETCH NEXT FROM curOrder INTO @customer_name@order_name
    END

    CLOSE curOrder
    DEALLOCATE curOrder

    运行结果:

    C2 O2 by C2
    C1 O3 by C1
    C2 O4 by C2
    C1 O1 by C1
    C1 O5 by C1
    C2 O6 by C2

    专注于自动化、性能研究,博客为原创,转载请注明文章来源于:http://www.cnblogs.com/Automation_software/ 只求在IT界有一个清闲的世界让我静心的去专研,不求功名利禄,只为心中的那份成就感及自我成长、自我实现的快感。
  • 相关阅读:
    【BZOJ3437】小P的牧场(动态规划,斜率优化)
    【BZOJ3156】防御准备(动态规划,斜率优化)
    【BZOJ2727】双十字(动态规划,树状数组)
    【BZOJ4361】isn(动态规划,容斥)
    【BZOJ1068】压缩(动态规划)
    【BZOJ4654】【NOI2016】国王饮水记(动态规划,斜率优化)
    【BZOJ2138】stone(线段树,Hall定理)
    【BZOJ4651】【NOI2016】网格(Tarjan,哈希)
    【Loj#535】花火(线段树,扫描线)
    【BZOJ4200】【NOI2015】小园丁与老司机(动态规划,网络流)
  • 原文地址:https://www.cnblogs.com/Automation_software/p/2003332.html
Copyright © 2020-2023  润新知