SQL string comma-separated functions

Source: Internet
Author: User

After SQL-function is created, the output results of the function database are separated by commas (,). During Development, many parameters with comma (,) are passed in as parameters (this is not recommended when data is large)

For example, search for data with the name "Zhang San, Li 'er" and process this parameter in the database.

FunctionCodeAs follows:

View code

 Create   Function   [  DBO  ] . [  Fnsplitstr  ] (
@ Stext Nvarchar ( Max ),
@ Sdelim Char ( 1 )
)

Returns @ Retarray Table (
Value Varchar ( 100 )
)
As
Begin
Declare
@ Posstart Bigint ,
@ Posnext Bigint ,
@ Vallen Bigint ,
@ Svalue Nvarchar ( 100 );

If @ Sdelim Is Null
Begin
If Len ( @ Stext ) > 100 Set @ Stext = Substring ( @ Stext , 1 , 100 )

Insert @ Retarray (Value)
Values ( @ Stext );
End
Else
Begin
Set @ Posstart = 1 ;

While @ Posstart <= Len ( @ Stext )
Begin
Set @ Posnext = Charindex ( @ Sdelim , @ Stext , @ Posstart );

If @ Posnext <= 0
Set @ Vallen = Len ( @ Stext ) - @ Posstart + 1 ;
Else
Set @ Vallen = @ Posnext - @ Posstart ;

Set @ Svalue = Substring ( @ Stext , @ Posstart , @ Vallen );
Set @ Posstart = @ Posstart + @ Vallen + 1 ;

If Len ( @ Svalue ) > 0
Begin
If Len ( @ Svalue ) > 100 Set @ Svalue = Substring ( @ Svalue , 1 , 100 )

Insert @ Retarray (Value)
Values ( @ Svalue );
End
End
End
Return
End

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.