In SQL Server, a string that is separated by a comma "," is converted to a table and applied with the in condition

Source: Internet
Author: User
Tags first string

string AA="1,2,3"; string sqltxt="Select*  from where inch ("+AA+") ";

It is possible to convert a string such as "one-way" to a temporary table with one column, 3 rows, and one item in each row (separated by commas)

This function can be written like this:

GO/** * * * object:userdefinedfunction [dbo].    [Strtotable] Script DATE:2016/3/1 18:53:35 * * * * **/SETAnsi_nulls onGOSETQuoted_identifier onGOALTER Function [dbo].[strtotable](@str varchar( +))Returns @tableName Table(IDvarchar( -)) as--This function is used to convert multiple data strings separated by commas into a single column of a table, for example, the string ' 1,2,3,4,5 ' will program a table, this tableBeginSet @str = @str+','Declare @insertStr varchar( -)--the first string after interceptionDeclare @newstr varchar( +)--string remaining after the first string is interceptedSet @insertStr =  Left(@str,charindex(',',@str)-1)Set @newstr = Stuff(@str,1,charindex(',',@str),"')Insert @tableName Values(@insertStr) while(Len(@newstr)>0)begin   Set @insertStr =  Left(@newstr,charindex(',',@newstr)-1)   Insert @tableName Values(@insertStr)   Set @newstr = Stuff(@newstr,1,charindex(',',@newstr),"')EndReturnEND

And then the SQL statement can do that.

Declare str Vchar (+)setstr='All-in-all' Select *  from where inch (Select from strtotable (@str))

In SQL Server, a string that is separated by a comma "," is converted to a table and applied with the in condition

Related Article

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.