1

我是在 SQL Server 中使用循环的新手。我只是想问为什么我的代码不起作用?我试图在一个循环中包含 if 语句,它将继续处理,直到它得到它想要的。感谢您的任何回复!

DECLARE @SubjectCategoryID bigint
DECLARE @ParentID bigint
DECLARE @EntityID bigint
DECLARE @isLocation int
DECLARE @tempTable TABLE (ParentID bigint, isLocation int) 
DECLARE @projectCodesTable TABLE (Contingency nvarchar(max), Provincial nvarchar(max), HQAdmin nvarchar(max))    
DECLARE @count int

Select @SubjectCategoryID = SubjectCategoryID, @EntityID = EntityID  from t_Project WHERE Code = '1000296'
SET @count = 0
SET @isLocation = 0

WHILE (@isLocation = 1)
BEGIN
    DELETE FROM @tempTable
    IF @SubjectCategoryID = 150     -- Village
    BEGIN
        INSERT INTO @tempTable
            SELECT CommunityID, IsLocation from t_Loc_Village WHERE VillageID = @EntityID

        Select @EntityID = ParentID, @isLocation = isLocation From @tempTable
        SET @SubjectCategoryID = 140
    END
    ELSE IF @SubjectCategoryID = 140    --- Community
    BEGIN
        INSERT INTO @tempTable
            SELECT CityTownID, IsLocation from t_Loc_Community WHERE CommunityID = @EntityID

        Select @EntityID = ParentID, @isLocation = isLocation From @tempTable
        SET @SubjectCategoryID = 135
    END
    ELSE IF @SubjectCategoryID = 135    --- City/Town
    BEGIN
        INSERT INTO @tempTable
            SELECT ProvinceID, IsLocation from t_Loc_CityTown WHERE CityTownID = @EntityID

        Select @EntityID = ParentID, @isLocation = isLocation From @tempTable
        SET @SubjectCategoryID = 130
    END
    ELSE IF @SubjectCategoryID = 130    --- Province
    BEGIN
        INSERT INTO @tempTable
            SELECT RegionalOfficeID, IsLocation from t_Loc_Province WHERE ProvinceID = @EntityID

        Select @EntityID = ParentID, @isLocation = isLocation From @tempTable
        SET @SubjectCategoryID = 210
    END
    ELSE IF @SubjectCategoryID = 210    --- Regional Office
    BEGIN
        INSERT INTO @tempTable
            SELECT CountryID, IsLocation from t_RegionalOffice WHERE RegionalOfficeID = @EntityID

        Select @EntityID = ParentID, @isLocation = isLocation From @tempTable
        SET @SubjectCategoryID = 100
    END
    ELSE IF @SubjectCategoryID = 100    --- Country
    BEGIN
        INSERT INTO @tempTable
            SELECT 0, IsLocation from t_Loc_Country WHERE CountryID = @EntityID

        Select @EntityID = ParentID, @isLocation = isLocation From @tempTable
        SET @SubjectCategoryID = 0
    END
END

Select * from @tempTable
4

1 回答 1

2

您的代码不会进入 while 循环,因为您已isLocation=0在开头设置并检查while(isLocation=1).尝试更改您的 while 循环逻辑。使用GOTO或模拟do while循环。请参阅:在 SQL Server 2008 中执行 while 循环以获取更多信息。

于 2013-08-14T07:42:13.627 回答