Last active
August 2, 2016 13:25
-
-
Save Slavenin/9b56da682340b67cc6007256ec89e8c0 to your computer and use it in GitHub Desktop.
simpe sql cursor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @eNum FLOAT | |
DECLARE @dNum NVARCHAR(10) | |
DECLARE @tNum FLOAT | |
DECLARE @level INT | |
DECLARE @counter INT | |
DECLARE @t TABLE ( | |
id INT | |
,eNum FLOAT | |
,dNum NVARCHAR(10) | |
,tNum FLOAT | |
,[level] INT | |
); | |
DECLARE @data TABLE ( | |
eNum FLOAT | |
,dNum NVARCHAR(10) | |
,tNum FLOAT | |
,[level] INT | |
); | |
INSERT INTO @data | |
values | |
(1.1, '1.1.1',1.2), | |
(1.2, '1.2.1',2.1), | |
(1.3, '1.3.3',(null)), | |
(1.3, '1.3.12',(NULL)), | |
(1.3, '1.3.11',(null)), | |
(1.3, '1.3.15',(null)), | |
(1.3, '1.3.8',(null)), | |
(1.3, '1.3.2',(null)), | |
(1.3, '1.3.13',(null)), | |
(1.3, '1.3.14',(null)), | |
(1.3, '1.3.7',(null)), | |
(1.3, '1.3.9',(null)), | |
(1.3, '1.3.5',(null)), | |
(1.3, '1.3.6',(null)), | |
(1.3, '1.3.10',(null)), | |
(1.3, '1.3.1',(null)), | |
(1.3, '1.3.4',(null)), | |
(2.1, '2.1.4',2.2), | |
(2.1, '2.1.3',2.2), | |
(2.1, '2.1.1',2.2), | |
(2.1, '2.1.6',2.2), | |
(2.1, '2.1.2',2.2), | |
(2.1, '2.1.7',2.2), | |
(2.1, '2.1.5',2.1), | |
(2.2, '2.2.18', 3.1), | |
(2.2, '2.2.5', 3.1), | |
(2.2, '2.2.15', 3.1), | |
(2.2, '2.2.4', 3.1), | |
(2.2, '2.2.12', (null)), | |
(2.2, '2.2.7', 3.1), | |
(2.2, '2.2.19', 3.1), | |
(2.2, '2.2.21', 3.1), | |
(2.2, '2.2.11', 2.1), | |
(2.2, '2.2.16', 3.1), | |
(2.2, '2.2.13', (null)), | |
(2.2, '2.2.2', 3.1), | |
(2.2, '2.2.6', 3.1), | |
(2.2, '2.2.1', 3.1), | |
(2.2, '2.2.20', 3.1), | |
(2.2, '2.2.14', 3.1), | |
(2.2, '2.2.17', 3.1); | |
/*Объявляем курсор*/ | |
DECLARE @CURSOR CURSOR | |
/*Заполняем курсор*/ | |
SET @CURSOR = CURSOR SCROLL | |
FOR SELECT | |
* | |
FROM @data ORDER BY eNum, dNum | |
OPEN @CURSOR | |
FETCH NEXT FROM @CURSOR INTO @eNum, @dNum, @tNum, @level | |
SET @counter = 0; | |
INSERT INTO @t (id, eNum, dNum, tNum, [level]) | |
SELECT | |
@counter | |
,@eNum | |
,@dNum | |
,@tNum | |
,@level | |
WHILE @@fetch_status = 0 | |
BEGIN | |
IF NOT EXISTS (SELECT | |
1 | |
FROM @t | |
WHERE eNum = @tNum) | |
BEGIN | |
SET @counter = @counter +1 | |
INSERT INTO @t (id, eNum, dNum, tNum, [level]) | |
SELECT | |
@counter | |
,eNum | |
,dNum | |
,tNum | |
,1 + @level | |
FROM @data d | |
WHERE d.eNum = @tNum | |
END | |
FETCH NEXT FROM @CURSOR INTO @eNum, @dNum, @tNum, @level | |
END | |
CLOSE @CURSOR | |
SELECT | |
* | |
FROM @t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment