0

我有一个游标,我想遍历一个临时表,并将每条记录合并到另一个表中。

我不能让这个游标只是循环遍历记录并返回一个计数。

DECLARE @curCatalogID int
DECLARE @curNomenclature varchar(200)
DECLARE @curMainCategory varchar(200)
DECLARE @curSubCategory varchar(200)
DECLARE @curManufacturer varchar(200)
DECLARE @curModelNo varchar(200)
DECLARE @curPrice varchar(200)
DECLARE @curProductDesc varchar(2000)
DECLARE @curImage varchar(200)
DECLARE @curPDFName varchar(200)
DECLARE @curInventory varchar(200)
DECLARE @curBatchID int
DECLARE @curAuditID int

DECLARE @nCnt int
SET @nCnt = 0

DECLARE import_loop CURSOR FOR
SELECT * FROM tblCatalogStaging

OPEN import_loop
FETCH NEXT FROM import_loop 
INTO    @curCatalogID,
        @curNomenclature,
        @curMainCategory,
        @curSubCategory,
        @curManufacturer,
        @curModelNo,
        @curPrice,
        @curProductDesc,
        @curImage,
        @curPDFName,
        @curInventory,
        @curBatchID,
        @curAuditID

WHILE @@FETCH_STATUS = 0
BEGIN

SET @nCnt = @@ROWCOUNT;

        FETCH NEXT FROM import_loop 
        INTO    @curCatalogID,
        @curNomenclature,
        @curMainCategory,
        @curSubCategory,
        @curManufacturer,
        @curModelNo,
        @curPrice,
        @curProductDesc,
        @curImage,
        @curPDFName,
        @curInventory,
        @curBatchID,
        @curAuditID

END
CLOSE import_loop
DEALLOCATE import_loop

SELECT @nCnt

它应该只返回 2036 的 1 个值(临时表中的行数),但我会返回 2036 行受影响,4072 行受影响等

4

3 回答 3

2

我不太确定@@ROWCOUNT 是否打算在 CURSOR 中使用。

你可能有更好的运气:

DECLARE @nCnt INT
SET @nCnt = 0
...
SET @nCnt = @nCnt + 1;

注意:TRIGGER 可能是对行插入/更新进行此验证的正确位置。除非你真的只希望验证有时发生。(此外,您将提出 SQL 错误,而不是异常)

于 2012-07-02T19:54:35.563 回答
0

我不确定它是否像这样简单,但你只是想要:

select count (*) FROM tblCatalogStaging
于 2012-07-02T19:34:45.507 回答
0

@@Rowcount provides the number of rows that were affected by the last statemenet to be executed. I do not think this is what you want, and I would agree with ebyrob about just using a counter variable.

But that is if you really need to do this in a cursor. AS marc_s suggest, you may want to rework your actual procedure so that it is using sets. If that is not possible and you need to, as you said in your response, deal with exceptions in your loop, you may want to look at Phil Factors recent article on that topic.

于 2012-07-02T20:09:56.537 回答