title: How to replace cursor inside Stored Procedure for faster Execution in MS SQL?
body: <p>I have written the below code for splitting string, but it takes a long time to execute. Please help me re-write my code to optimize the query. I have tried hard to find the result, but i didn't get how to apply the logic to replace the cursor. </p>
  
  <pre><code>declare @table as nvarchar(50),@column as nvarchar(max),@delimiter
  as nvarchar(1),@tablekey as nvarchar(max)
  
  BEGIN  
  SET NOCOUNT ON;  
   set @table='QAT_Tsentences'
   set @column='SentenceElID'
   set @delimiter='|'
   set @tablekey='ID'
  
   declare @sql as nvarchar(max), @tabkey as nvarchar(max),  @txt as 
   nvarchar(1000), @txtSplitted as nvarchar(255)  
   DECLARE @pos integer--, @delimiter as nchar(1)  
   DECLARE @Leftpiece nvarchar(255), @Rightpiece as nvarchar(255)  
  
  
   CREATE TABLE #t(tablekey  nvarchar(max), txt nvarchar(1000))  
   set @sql= 'INSERT #t select '+@tablekey+','+@column+' from '+@table+' where 
   '+@column+' is not null'  
  
    exec(@sql)  
  
    drop table QAT_txtsplitted  
    CREATE TABLE QAT_txtsplitted(tablekey  nvarchar(max), txt [nvarchar] 
   (max), txtSplitted [nvarchar](max), ID INT NOT NULL IDENTITY(1,1))  
  
  
  
    DECLARE c1 CURSOR   
    FOR  
     SELECT tablekey, txt  
      FROM #t  
  
     OPEN c1  
  
     FETCH NEXT FROM c1  
     INTO @tabkey,@txt  
      While (@@Fetch_status = 0)  
      BEGIN   
  
      SET @Rightpiece = @txt  
      IF RIGHT(RTRIM(@Rightpiece),1) &lt;&gt; @delimiter  
      SET @Rightpiece = @Rightpiece  + @delimiter  
      SET @pos =  CHARINDEX(@delimiter, @Rightpiece)  
  
      WHILE @pos &lt;&gt; 0   
      BEGIN  
      SET @Leftpiece = LEFT(@Rightpiece, @pos - 1)  
       INSERT INTO  QAT_txtsplitted (tablekey,txt,txtsplitted) VALUES  
        (@tabkey,@txt, @Leftpiece);  
        SET @Rightpiece = STUFF(@Rightpiece, 1, @pos, '')  
        SET @pos =  CHARINDEX(@delimiter, @Rightpiece)  
         END  
         FETCH NEXT FROM c1  
         INTO @tabkey,@txt  
  
         END  
  
    CLOSE c1  
       DEALLOCATE c1  
       drop table #t  
       nchar(1),@tablekey as decimal(15))  
       print 'table results : QAT_txtsplitted'  
  
       END 
  </code></pre>
  
  <p>Please find below my result where i have tried to split for a particular tablekey.
       <a href="https://i.stack.imgur.com/lSSNY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lSSNY.png" alt="enter image description here"></a></p>