嵌套游标,While循环SQL

时间:2015-07-20 05:42:10

标签: sql while-loop cursor sql-insert

我正在尝试将数据插入两个表中(两个表上一次100到150行)。第一个表主键有一个引用第二个表外键.I读取Cursor有问题@@ Fetch_Status是全局变量。哪个是在表格Cursor或While Loop或其他任何表格中循环和进行数据插入的最佳方法。

CREATE TABLE Table1
(
FirstTablePK [int] NOT NULL, --Mannual Increment(Not Identity)
Description [varchar](100) NOT NULL,
CONSTRAINT PK_Table1 PRIMARY KEY CLUSTERED (FirstTablePK)
)

CREATE TABLE Table2
(
SecondTablePK [int] NOT NULL, --Mannual Increment(Not Identity)
FirstTablePK [int] NOT NULL, -- Foreign Key Reference with Table1
Description [varchar](100) NOT NULL,
CONSTRAINT PK_Table2 PRIMARY KEY CLUSTERED (SecondTablePK),
CONSTRAINT FK_Table1 FOREIGN KEY (FirstTablePK) REFERENCES Table1(FirstTablePK)
)

先谢谢。 哈里

1 个答案:

答案 0 :(得分:0)

游标通常不用于查找外键。使用基于集合的查询更快更容易:

insert  into SaleOrder
        (remarks, product_id, customer_id, ...)
select  'please deliver fast'
,       (select id from Products where name = 'Car Oil')
,       (select id from Customers where name = 'India Corp')
,       ...