Comma Delimited SQL string Need to separated

前端 未结 11 1947
[愿得一人]
[愿得一人] 2020-12-20 23:39

I have this string that i am getting from .net application A,B,C,D,E,F,

I wanted to write a sql select statement like

set @string = \'A,B,C,D,E,F\'

         


        
相关标签:
11条回答
  • 2020-12-21 00:28

    You have several options:

    • If you are OK with it, just compose the SQL statement dynamically before making call to SQL. There is a limitation on the number of values in the IN statement
    • Use Table-valued UDF that splits the string and returns the table. Then your query would either use IN or better just JOIN statement (among other implementations I favor SQL User Defined Function to Parse a Delimited String).

    The you code would be:

    select     tbl_test.*
    from       tbl_test 
    inner join fn_ParseText2Table(@string) x
           on  tbl_test.code = x.txt_value 
    
    • Since you use SQL Server 2005, you can write CLR Table-valued UDF that would do the same job as previous UDF does, which would be much smaller and faster since string operations in CLR are way better handled that in SQL.
    0 讨论(0)
  • 2020-12-21 00:29

    Create a User Defined Function that takes the string as input and returns a table:

    create function [dbo].[f_SplitString] (@str as varchar (1000))
    returns @t table (value varchar (50))
    etc...
    

    Then adjust your Select statement:

    select * from tbl_test 
    where tbl_test.code in (select value from f_SplitString(@string))
    
    0 讨论(0)
  • 2020-12-21 00:31

    I know this is an old question, but I thought I would post an answer to it anyway. I never liked passing in comma delimited string values, so I have used XML in the past and used a join statement on the xml like so:

    declare @xml as xml
    set @xml = '<v id="key1" /><v id="key2" /><v id="key3" />'
    select
        t.*
    from
        mytable t join @xml.nodes('/*') x(n)
        on n.value('@id','varchar(50)') = t.mykey
    
    0 讨论(0)
  • 2020-12-21 00:38

    I think, the easiest way is as below,

    • Option1:

      set @string = '''A','B','C','D','E','F'''
      
      Exec ('select * from tbl_test 
      where tbl_test.code in ('+@string+')')
      
    • Option2:

      set @string = '''A','B','C','D','E','F'''
      
      DECLARE @SQL NVARCHAR(MAX)
      
      SET @SQL='select * from tbl_test 
      where tbl_test.code in ('+@string+')'
      
      exec sp_executesql @SQL;
      
    0 讨论(0)
  • 2020-12-21 00:40

    Very frequently asked question! What you want is a table-valued function.

    But don't reinvent the wheel by writing your own, I found dozens just by Googling sql split. Here's one from Microsoft:

    http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput

    I used to use dynamic SQL for this, but that meant I had to dig up the code and copy it into each new app. Now I don't even have to think about it.

    0 讨论(0)
提交回复
热议问题