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

后端 未结 14 825
情深已故
情深已故 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条回答
  •  Happy的楠姐
    2020-12-28 13:18

    If you have the IDs stored in a temp table (which can be done by some C# function or simple SQL) then the problem becomes easy and doable in SQL.

    select "all exist"
    where (select case  when count(distinct t.id) = (select count(distinct id) from #products) then "true" else "false" end
        from ProductTable t, #products p
        where t.id = p.id) = "true"
    

    This will return "all exists" when all the products in #products exist in the target table (ProductTable) and will not return a row if the above is not true.

    If you are not willing to write to a temp table, then you need to feed in some parameter for the number of products you are attempting to find, and replace the temp table with an 'in'; clause so the subquery looks like this:

    SELECT "All Exist"
    WHERE(
            SELECT case when count(distinct t.id) = @ProductCount then "true" else "false" 
            FROM ProductTable t 
            WHERE t.id in (1,100,10,20) -- example IDs
    ) = "true"
    

提交回复
热议问题