设置NOCOUNT和游标

时间:2009-10-07 20:52:31

标签: sql sql-server tsql cursor nocount

我有一个存储过程调用几个存储过程,每个过程都将虚拟数据插入到一个表中。它的工作正常,但是对于光标中的每个循环,会调出一行结果 - 只显示ClubcardId = 2,ClubcardId = 3等。

我已经使用了SET NOCOUNT ON,但这似乎没有帮助。我正在寻找这个存储过程来创建几百万行,所以SQL打印每行的结果将是一个问题。

有人可以建议如何防止输出显示。我已经复制了下面的父存储过程。我可以确定显示器不是来自子存储过程 - lap_CreateClubcardTransaction。

如果我改变:

DECLARE Clubcard_Cursor CURSOR FAST_FORWARD FOR
SELECT ClubcardId FROM Clubcard

......来:

DECLARE Clubcard_Cursor CURSOR FAST_FORWARD FOR
SELECT ClubcardId as 'TEST' FROM Clubcard

...然后我得到了光标每一行的值'TEST'。

这是父存储过程:

ALTER PROCEDURE [dbo].[lap_CreateDummyData]
AS  
SET NOCOUNT ON

DECLARE @NumberOfCustomers bigint
DECLARE @NumberOfTransactions bigint

SET @NumberOfCustomers = 50000
SET @NumberOfTransactions = 10

EXEC lap_CreateCustomer @NumberOfCustomers = @NumberOfCustomers;
EXEC lap_CreateCustomerPreference @NumberOfCustomers = @NumberOfCustomers;
EXEC lap_CreateClubCard @NumberOfCustomers = @NumberOfCustomers;
EXEC lap_CreateClubCardOffer @NumberOfCustomers = @NumberOfCustomers;

--get static data details to use when creating transaction records
DECLARE @TransactionType tinyint
DECLARE @TransactionReasonID tinyint
DECLARE @TescoStoreID int
DECLARE @PartnerID bigint
DECLARE @PartnerOutletID bigint
DECLARE @ClubcardID bigint

SET @TransactionType = (SELECT TOP 1 TransactionType FROM TransactionType)
SET @TransactionReasonID = (SELECT TOP 1 TransactionReasonID FROM TransactionReason)
SET @TescoStoreID = (SELECT TOP 1 TescoStoreId FROM TescoStore)
SET @PartnerID = (SELECT TOP 1 PartnerID FROM PartnerOutlet)
SET @PartnerOutletID = (SELECT TOP 1 PartnerOutletID FROM PartnerOutlet)

DECLARE Clubcard_Cursor CURSOR FAST_FORWARD FOR
  SELECT ClubcardId FROM Clubcard

OPEN Clubcard_Cursor
FETCH NEXT FROM Clubcard_Cursor 
  INTO @ClubcardID SET NOCOUNT ON

  WHILE @@FETCH_STATUS = 0
  BEGIN
    EXEC lap_CreateClubcardTransaction @NumberOfTransactions = @NumberOfTransactions, @ClubcardID = @ClubcardID, @TransactionType = @TransactionType, @TransactionReasonID = @TransactionReasonID, @TescoStoreId = @TescoStoreID, @PartnerID = @PartnerID, @PartnerOutletID = @PartnerOutletID;
    FETCH NEXT FROM Clubcard_Cursor;
  END;

CLOSE Clubcard_Cursor;
DEALLOCATE Clubcard_Cursor;

3 个答案:

答案 0 :(得分:4)

您还需要将FETCH引导到循环中的变量中:

WHILE ...
BEGIN
  ...
  FETCH NEXT FROM Clubcard_Cursor INTO @ClubcardID
END

答案 1 :(得分:1)

在任何情况下,我都不会使用游标一次插入一行数百万行。那需要几个小时。这是光标使用不当的一个例子。创建一个将执行基于集合的操作的proc。

答案 2 :(得分:0)

SET NOCOUNT ON在获取内部无用,因此请从那里删除它。似乎lap_CreateClubcardTransaction在其代码中包含一个SELECT语句。你能检查一下这是不是真的吗?