开发者

SQL Cursor Processing Control Break logic

Is this how we still handle control break logic in sql cursors

Basically, what i want to do is loop through a list of accounts and if the next account name is the same as the previous one do many things else do many other things.

The sample below just lists all the accounts and how many times they occur in the list. Ideally, I'll do more processing in each case (like call several stored procs). Is there another way to do this?

DECLARE @CompanyName NVARCHAR(255)
DECLARE @CompanyNameHold NVARCHAR(255)
DECLARE @TESTCOUNT INT
DECLARE @TOTALCOUNT INT

SELECT @CompanyNameHold = ''
SELECT @TESTCO开发者_如何学运维UNT = 0
SELECT @TOTALCOUNT = 0

DECLARE ImportCursor CURSOR FOR
SELECT [Company Name]
  FROM [MyDB].[dbo].[AccountsToImport]
  ORDER BY [Company Name]


OPEN ImportCursor
FETCH NEXT FROM ImportCursor INTO @CompanyName

WHILE @@FETCH_STATUS = 0
BEGIN


    --Check HoldCompanyName = CompanyName   
    IF (@CompanyName <> @CompanyNameHold)   
    BEGIN   
        --PROCESS NEW ACCOUNT
        IF @TESTCOUNT = 0 --PRIMER
            SET @CompanyNameHold = @CompanyName
        ELSE        
            PRINT CAST(@TESTCOUNT AS NVARCHAR) + ' - ' + @CompanyNameHold 

        SET @TESTCOUNT = 1
    END
    ELSE
    BEGIN
        --ADD TO EXISTING
        SET @TESTCOUNT = @TESTCOUNT + 1
    END


    --Move CompanyName to HoldCompanyName
    SET @CompanyNameHold = @CompanyName
    SET @TOTALCOUNT = @TOTALCOUNT + 1

    FETCH NEXT FROM ImportCursor INTO @CompanyName
END
    --Process Last Record 
    PRINT CAST(@TESTCOUNT AS NVARCHAR) + ' - ' + @CompanyNameHold 

CLOSE ImportCursor
DEALLOCATE ImportCursor


You can query the number of rows per company without a cursor:

select  [Company Name]
,       count(*) as RowsPerCompany
from    MyDB.dbo.AccountsToImport
group by
        [Company Name]

But to call a stored procedure for each row, a cursor is required. You can call any number of stored procedures while looping over the cursor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜