Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update in loop sql

I am supposed to make a loop in which I will update the tag and add the registration number to it

it looks like

LP Text
1 ‘Mamma mia #XX’
2 ‘Joe is my best #XX friend’
3 Hi hey haloo’
4 ‘one #XX two #XX three #XX’
5 ‘best phone ever’
6 ‘Nice im love it #XX what we do next #XX’

it should look like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

LP Text
1 ‘Mamma mia #XX[01]’
2 ‘Joe is my best #XX[02] friend’
3 Hi hey haloo’
4 ‘one #XX[03] two #XX[04] three #XX[05]’
5 ‘best phone ever’
6 ‘Nice im love it #XX[06] what we do next #XX[07]’

>Solution :

A bit ugly, but loops should be the last resort.

Example

Declare @YourTable Table ([LP] int,[Text] varchar(50))  Insert Into @YourTable Values 
 (1,'Mamma mia #XX')
,(2,'Joe is my best #XX friend')
,(3,'Hi hey haloo')
,(4,'one #XX two #XX three #XX')
,(5,'best phone ever')
,(6,'Nice im love it #XX what we do next #XX')

;with cte as (
Select * 
      ,Seq = sum(case when RetVal like '#%' then 1 else 0 end) over ( order by RN,RetSeq)
      ,Pos = charindex(' ',RetVal+' ')
 From  (
        Select *
              ,RN = row_number() over( order by LP) 
         from @YourTable
       ) A 
 Cross Apply (
            Select RetSeq = [Key]+1
                  ,RetVal = trim(Value)
             From  OpenJSON( '["'+replace(string_escape(replace([Text],'#','|||#'),'json'),'|||','","')+'"]' )

             ) B
)
Select LP
      ,NewVal = string_agg(
                case when RetVal not like '#%' then RetVal
                     else stuff(RetVal+' ',Pos,0,concat('[',format(Seq,'00'),'] '))
                end
                ,' ') WITHIN GROUP (ORDER BY RN,Seq)
 From  cte
 Group By LP
 Order By LP

Results

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading