Add List to a mysql parameter

后端 未结 9 1321
暗喜
暗喜 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

    You have a few options here (in order of preference):

    1. Use a database that supports table valued parameters. This is the only way to get the exact syntax you want.
    2. The data has to come from somewhere: either your database, user action, or machine-generated source.

      • If the data is already in your database, use a subquery instead.
      • For other machine generated data, use BULK INSERT, SqlBulkCopy, or your database's preferred bulk import tools.
      • If it's created by the user, add it to a separate table on each individual user action, and then use a sub query.

        An example of this is a shopping cart. A user might select several items to purchase. Rather than keep these in the app and need to add all the items to an order in one go when they check out, add each item to a table in the db as the user selects or changes it.

    3. Have an sql user defined function that unpacks a string parameter into a table and returns that table as a set you can use with an IN() expression. See the linked article below for more detailed information on how this works.
    4. Build a string list or parameter list dynamically on the client (as shown in other answers). Note that this is my least preferred option, as the code it creates tends to be crazy-vulnerable to sql injection issues.

    The definitive (and I mean definitive) work on the subject is here:

    http://www.sommarskog.se/arrays-in-sql.html

    The article long, but in a good way. The author is a sql server expert, but the concepts on the whole apply to MySQL as well.

提交回复
热议问题