我是在 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