2011-02-02 49 views
0

我有一個特定的問題。用於循環遞歸層次結構的T-SQL存儲過程

我的存儲過程無法正常工作。我會告訴你的程序,數據庫和參數:

ALTER PROCEDURE [dbo].[ManufacturerParentToChild] 

@ServiceProviderId int, 
@CarmakerId int 

AS BEGIN

SET NOCOUNT ON; 

DECLARE @childSPPId int, @isDeleted bit 

DECLARE ServiceProviderChildren_Cursor CURSOR FOR 

SELECT ServiceProviderId, isDeleted 
FROM ServiceProvider 
WHERE ParentServiceProviderId = @ServiceProviderId; 

OPEN ServiceProviderChildren_Cursor; 

FETCH NEXT FROM ServiceProviderChildren_Cursor INTO @childSPPId, @isDeleted; 

WHILE @@FETCH_STATUS = 0 
    BEGIN 
     IF @ServiceProviderId > 0 
     BEGIN 
      EXEC ManufacturerParentToChild @childSPPId, @CarmakerId; 

      IF (SELECT COUNT(*) FROM dbo.CarmakerPartnership WHERE ServiceProviderId = @childSPPId AND CarmakerId = @CarmakerId) = 0 
      BEGIN 
       IF (@isDeleted = 0) 
       BEGIN 
        INSERT INTO dbo.CarmakerPartnership (CarmakerId, ServiceProviderId, CreatedBy, ChangedBy, ValidityPeriodFrom, ValidityPeriodTo) VALUES (@CarmakerId, @childSPPId, SYSTEM_USER, SYSTEM_USER, '01.01.1900 00:00:00', '31.12.9999 23:59:00.000') 
       END 
      END 
     END 
     FETCH NEXT FROM ServiceProviderChildren_Cursor INTO @childSPPId; 
    END; 
CLOSE ServiceProviderChildren_Cursor; 
DEALLOCATE ServiceProviderChildren_Cursor; END 

你看我的存儲過程,上述。

數據庫表服務提供商有7行:

ServiceProviderId名稱ParentServiceProviderId請將isDeleted
1 '父' NULL 0
2 'Child1' 1 0
3 'CHILD2' 1 0
4「Child4 '2 0
5 'Child5' 3 0
6 'child6' 4 0
7 'Child7' 6 0

該Paramater得到的值:

@ServiceProviderId = 1 @CarmakerId = 5

的步驟插入ServiceProviderId 7,6,4和2到CarmakerPartnerShip但不插入3和5!

有沒有人知道爲什麼遞歸循環跳槽通過ServiceProviderId = 2的孩子但不跳槽通過ServiceProviderId = 3的孩子?

謝謝你的幫助和對不起我的英文不好!

如果您有任何問題,可以詢問我。

問候

亞歷

+0

對不起,我不這樣做光標! – 2011-02-02 11:22:48

+0

使用`EXISTS`而不是`SELECT COUNT(*)`檢查是否存在。這樣更有效率。可能會拋開遊標:-) – 2011-02-02 13:22:36

回答

1

在while塊讀取語句可能是原因。目前,它寫着:

FETCH NEXT FROM ServiceProviderChildren_Cursor INTO @childSPPId; 

嘗試替換它:

FETCH NEXT FROM ServiceProviderChildren_Cursor INTO @childSPPId, @isDeleted;