0

3106 Points

967 Posts Split Data in SQL Server String

25 minutes ago|LINK

Hi All,

I have two comma separated strings, one have control name and other have its values which i have send to stored procedure along with the table name in which data needs to be inserted.

Now, how can I split these strings and form a insert query in sql server 2008 ?

Also, I have one table in which i have maintained Control Value should be stored in which column ?

So I need to form insert query using this ? How can i do it ?

1 Answer 1

1

This function will help you to split strings:

CREATE function dbo.split(@value varchar(8000),@delim varchar(8000))
returns table
as
return
(
select d.value,
       d.orders,
       ivalue = convert(int, case when isnumeric(d.value)=1 and d.value not like '%[^0-9 +-]%' and len(replace(replace(replace(d.value,' ',''),'-',''),'+',''))<=10 then case when convert(bigint,d.value) between -2147483648 and 2147483647 then d.value end end)

    from
        (
            select   
                    value= replace(substring(value,
                                            idx,
                                            case when cnt>=0 then cnt end /* case для защиты от нехороших планов, когда сначала идет вычисление substring, а потом ограничивающее where по s_value.number between */
                                         )
                                 ,char(1),'')
                    ,orders=( datalength(left(value,idx-1))-datalength(replace(left(value,idx-1),@delim,''))
                            )/datalength(@delim)
                from (
                       select number
                             ,idx
                             ,cnt = charindex(@delim,value, number + 1) - number - datalength(@delim)
                             ,value 
                          from 
                                (
                                   select number
                                         ,idx = number + datalength(@delim)
                                         ,value = (select @delim+char(1)+@value+char(1)+@delim)
                                      from dbo.s_value
                                        where number between 1 and datalength( (select @delim+char(1)+@value+char(1)+@delim) ) - datalength(@delim)

                                ) t            
                          where substring(t.value, number, datalength(@delim)) = @delim         
                     ) t             
       ) d          
)


GO
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.