Passing parameter to SQL select statement IN clause acts weird.

前端 未结 4 1274
暗喜
暗喜 2021-01-21 11:38

I\'ve got the following query that returns 2 records (in DataSet\'s query builder)

SELECT        EmpID, Name, id
FROM          Users
WHERE        (CAST(id AS Var         


        
相关标签:
4条回答
  • 2021-01-21 11:57

    ('5688','5689') is an array of values.

    Defining String param = "'5688','5689'"; and using it as (@param) makes ('5688','5689') a string. Which wont work.

    0 讨论(0)
  • 2021-01-21 12:01

    Bibhas is correct. For me this worked:

    string param="'1234','4567'"; we can't use param as SQL Parameter(@param).

    command = new SqlCommand("SELECT * FROM table WHERE number IN (" + param + ")", connection);

    command.ExcecuteReader();

    0 讨论(0)
  • 2021-01-21 12:08

    A variable is not allowed in the IN clause.
    You are expecting the values as a comma delimited string you could use the split function (user defined and non-standard) to join them with the original tables:

    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=326300&SiteID=1

    For more information you can visit this

    0 讨论(0)
  • 2021-01-21 12:18

    The solution I found is quite simple, this works like a charm and there's no need for sps or other functions;

    SQL:

    SELECT whatever 
    FROM whatever
    WHERE (PATINDEX('%''' + CAST(id AS Varchar(20)) + '''%', @param) > 0)
    

    C#:

    String param = "'''1234'',''4567'''";
    dataTable1 = tableAdapter1.getYourValues(param);
    
    0 讨论(0)
提交回复
热议问题