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

后端 未结 14 800
情深已故
情深已故 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:17

    Where is this list of products that you're trying to determine the existence of? If that list exists within another table you could do this

    declare @are_equal bit
    declare @products int
    
    SELECT @products = 
         count(pl.id)
    FROM ProductList pl
    JOIN Products p
    ON pl.productId = p.productId
    
    select @are_equal = @products == select count(id) from ProductList
    

    Edit:

    Then do ALL the work in C#. Cache the actual list of products in your application somewhere, and do a LINQ query.

    var compareProducts = new List(){p1,p2,p3,p4,p5};
    var found = From p in GetAllProducts()
                Join cp in compareProducts on cp.Id equals p.Id
                select p;
    
    return compareProducts.Count == found.Count;
    

    This prevents constructing SQL queries by hand, and keeps all your application logic in the application.

提交回复
热议问题