Skip to content
Advertisement

How to remove While loop inside stored procedure in MS SQL Server? [closed]

I have a stored procedure with a cursor inside for the logic which is taking long time for execution . I have changed to while loop for faster execution but Even while loop takes so long time for the below query . Please help me to change a while loop for faster execution . I have updated the description for better understanding .

enter image description here

BEGIN
DECLARE @Modules TABLE
(
    ID INT IDENTITY(1,1)
    , ListElid NVARCHAR(250)
    , ListType NVARCHAR(250)
    , orderArray NVARCHAR(250)
    , LeftTSMKEY NVARCHAR(250)
)

declare @orderArray int, @LeftTSMKEY nvarchar(250), @ListElid nvarchar(250),  @ListType 
 nvarchar(250), @ListType_Prev nvarchar(250)  
 set @ListType_Prev=''  
  set @inc=0  

 INSERT INTO @Modules   select    ListElid, ListType,orderArray, LeftTSMKEY from QAT_ListElid order 
 by ListType,orderArray

DECLARE @Count INT, @Counter INT, @ListId NVARCHAR(250) --, @Listtype NVARCHAR(260), @orderArray 
NVARCHAR(260) , @LeftTSMKEY NVARCHAR(260)
SELECT @Count = COUNT(*) FROM @Modules m
SET @Counter = 1



WHILE @Counter <= @Count
BEGIN
    SELECT @ListId= ListElid, @Listtype = ListType , @orderArray = orderArray , @LeftTSMKEY = 
    LeftTSMKEY FROM @Modules m 
    WHERE ID = @Counter -- extracting values from the table by counternum



     if @ListType<>@ListType_Prev  
   begin  
  set @inc=0  
  set @ListType_Prev =@ListType  
   end  

   Else If @ListType=@ListType_Prev  
   begin  
  set @inc=@inc+1  
  End  

  if @inc <> @orderArray  
 begin  
 INSERT [QAT_ListElid2] ([ListElid],[ListType],[orderArray],[LeftTSMKEY])  
 values (@ListElid,@ListType,@inc,@LeftTSMKEY+CAST(@inc as nvarchar(10))+']')  
 End 


    SET @Counter = @Counter + 1
   END 
   end

Advertisement

Answer

Could be wrong, but looks like a “gaps and islands” problem.

  • We first check whether each row has the same ListType as the previous.

  • Then we create a Group number for each new stretch of values.

  • Then we get a rownumber partitioned on this grouping.

WITH Previous AS (
    SELECT *,
        CASE WHEN ListType = LAG(ListType) OVER (ORDER BY ID) THEN 1 END SamePrevious
    FROM QAT_ListElid
),
Grouped AS (
    SELECT *,
        COUNT(SamePrevious) OVER (ORDER BY ID ROWS UNBOUNDED PRECEDING) Grp
),
Numbered AS (
    SELECT *,
        ROWNUMBER() OVER (PARTITION BY Grp ORDER BY ID) - 1 rn
)
INSERT [QAT_ListElid2]
    (ListElid, ListType, orderArray, LeftTSMKEY)
select
    ListElid,
    ListType,
    rn,
    LeftTSMKEY + CAST(rn as nvarchar(10)) + ']'
from Grouped
WHERE orderArray <> rn
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement