【发布时间】:2013-08-16 01:12:50
【问题描述】:
我是在 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
【问题讨论】:
-
您能否提供每个表中的一些示例数据:
t_Loc_Village等? -
@isLocation 在哪里获得值 1 以使控件进入 WHILE 循环?
-
@ShaneHaw,所有这些表都有 LocationID、ParentID 和 isLocation 列。当我使用 LocationID 在特定表中找到数据时,相应的 ParentID 将是新的 LocationID(@entity 值),并将用于将其搜索到其他表。它就像层次结构级别。,我找到位置直到它到达 isLocation = 1 的位置。
-
@BijuP,我在每个 if 和 else if 语句之间设置 isLocation 的值..
标签: sql sql-server if-statement while-loop