Add List to a mysql parameter

后端 未结 9 1280
暗喜
暗喜 2020-12-14 02:36

I have this question about the MySqlParameter from the .NET connector.

I have this query:

SELECT * FROM table WHERE id IN (@parameter)
相关标签:
9条回答
  • 2020-12-14 03:18

    This doesn't work well for huge lists, but it is the only thing I have found that works if you have to pass a list in as a parameter.

    Instead of

    SELECT * FROM table WHERE id IN (@parameter)
    

    You have to do this:

    SELECT *
    FROM table
    WHERE INSTR(','+@parameter+',', ','+CAST(the_column AS CHAR) + ',')
    

    Then you can pass in your list with string.Join(",", intArray)

    It's a kludge, but it works.

    0 讨论(0)
  • 2020-12-14 03:22

    Answer from Mud only works for the first int in the parameter list. This means '2,1,3,4' won't work if id is 1 for example.

    See FIND_IN_SET() vs IN() .

    No comment possible by now but also see answer from Matt Ellen. Would edit his answer but can't. INSTR doesn't seem to work in a WHERE case with more than one id (returns only on result).

    But replacing INSTR with LOCATE make his solution work (with String.Join(",", intArray) as parameter added) ... UP VOTE from me:

    LOCATE(CONCAT(',' , CAST(id AS CHAR) , ',') , CONCAT(',' , CAST(@paramter AS CHAR) , ',')) <> 0
    
    0 讨论(0)
  • 2020-12-14 03:23

    you are going to have to iterate over your array and create the list yourself

    // no parameters
    var sb = new StringBuilder();
    for(int i=0;i<intArray.Length;i++)
    {
        sb.Append(intArray[i] + ",");// no SQL injection they are numbers
    }
    if (sb.Length>0) {sb.Length-=1;}
    string sql = "SELECT * FROM table WHERE id IN (" + sb.ToString() + ")";
    

    UPDATE: Having thought more about this I'll go back to my original answer (below) which is to use parameters. Optimisations of built queries and whatever the database engine can muster are up to you.

    // no parameters
    var sb = new StringBuilder();
    for(int i=0;i<intArray.Length;i++)
    {
        sb.AppendFormat("p{0},", i);// no SQL injection they are numbers
        connection.Command.Parameters.AddWithValue("p"+i, intArray[i]);
    }
    if (sb.Length>0) {sb.Length-=1;}
    string sql = "SELECT * FROM table WHERE id IN (" + sb.ToString() + ")";
    
    0 讨论(0)
提交回复
热议问题