示例 1
DECLARE @I INT,@COUNTVAR INT
SET @I = 1
DECLARE @Parent_Child TABLE(ID INT IDENTITY(1,1),ParentPositionID INT NULL,ChildPositionId Int)
INSERT INTO @Parent_Child(ParentPositionID,ChildPositionId)
SELECT DISTINCT PARENT_POSITION_ID,CHILD_POSITION_ID from tblPOSITION_HIERARCHY
--WHERE CHILD_POSITION_ID IN (--YOUR CONDITION IF ANY)
SELECT @COUNTVAR =COUNT(*) FROM @PTS_Parent_Child
DECLARE @int_SUPE_POSITION_ID INT, @int_CHILD_POSITION_ID INT
--loop through records here
WHILE @I <= @COUNTVAR
BEGIN
SELECT @int_SUPE_POSITION_ID=ParentPositionID,@int_CHILD_POSITION_ID=ChildPositionId FROM @Parent_Child WHERE ID=@I
--Whatever you want to do with records
SET @I=@I+1
END
示例 2
如果您可以使用临时表,这只是另一种方法。我已经亲自测试过了,它不会导致任何异常(即使临时表没有任何数据。)
CREATE TABLE #TempTable
(
ROWID int identity(1,1) primary key,
HIERARCHY_ID_TO_UPDATE int,
)
--INSERT DATA INTO TEMP TABLE USING INSERT INTO CLAUSE OR FOR EAXMPLE BELOW
--INSERT INTO #TempTable VALUES(1)
--INSERT INTO #TempTable VALUES(2)
--INSERT INTO #TempTable VALUES(4)
--INSERT INTO #TempTable VALUES(6)
--INSERT INTO ##TempTable VALUES(8)
DECLARE @MAXID INT
SET @COUNTER =1
SELECT @MAXID=COUNT(*) FROM #TempTable
--PRINT @MAXID
WHILE (@MAXID > 0)
BEGIN
--DO THE PROCESSING HERE
SELECT @HIERARCHY_ID_TO_UPDATE =PT.HIERARCHY_ID_TO_UPDATE FROM #TempTable PT WHERE ROWID=@COUNTER
--PRINT '@MAXID VALUE '
--PRINT @MAXID
SET @MAXID=@MAXID-1
SET @COUNTER =@COUNTER + 1
End
If(OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
BEGIN
DROP TABLE #TempTable
END