mercredi 20 mai 2015

Function to split a string at the first space after a certain character limit with sequence into multiple rows

I've been trying to make a T-SQL function that would behave just like in the title. I found some kind of function that resembles what I need, but I want to make it so, instead of searching in declarations, it searches in a column in certain table.

Here's a code from Microsoft forums that resembles what I need. It was made by Sarat Babu:

declare @str varchar(max)

set @str = 'Guidelines and recommendations for lubricating the required components of your Adventure Works Cycles bicycle. Component lubrication is vital to ensuring a smooth and safe ride and should be part of your standard maintenance routine. Details instructions are provided for each bicycle component requiring regular lubrication including the frequency at which oil or grease should be applied'

declare @data table (col varchar(100))
while (LEN(@str)>0)
begin

if (LEN(@str)<=50)
begin 
        insert into @data select @str
        set @str=''
end 
else 
begin 

insert into @data
select STUFF(@str,charindex(' ',SUBSTRING(@str,50,LEN(@str)))+50,LEN(@str),'')

set @str= STUFF(@str,1,charindex(' ',SUBSTRING(@str,50,LEN(@str)))+49,'')
end
end 
select * from @data

As I said, I want to make it so instead of declaring the text, it searches for it in a specific column of a table. Let's say ProductName column inside Products table.

Aucun commentaire:

Enregistrer un commentaire