SQL: Return “true” if list of records exists?

后端 未结 14 797
情深已故
情深已故 2020-12-28 12:49

An alternative title might be: Check for existence of multiple rows?

Using a combination of SQL and C# I want a method to return true if all products in a list exist

14条回答
  •  自闭症患者
    2020-12-28 13:28

    Your c# will have to do just a bit of work (counting the number of IDs passed in), but try this:

    select (select count(*) from players where productid in (1, 10, 100, 1000)) = 4
    

    Edit:

    4 can definitely be parameterized, as can the list of integers.

    If you're not generating the SQL from string input by the user, you don't need to worry about attacks. If you are, you just have to make sure you only get integers. For example, if you were taking in the string "1, 2, 3, 4", you'd do something like

    String.Join(",", input.Split(",").Select(s => Int32.Parse(s).ToString()))
    

    That will throw if you get the wrong thing. Then just set that as a parameter.

    Also, be sure be sure to special case if items.Count == 0, since your DB will choke if you send it where ParameterID in ().

提交回复
热议问题