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

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

    If you are using SQL Server 2008, I would create a stored procedure which takes a table-valued parameter. The query should then be of a particularly simple form:

    CREATE PROCEDURE usp_CheckAll 
        (@param dbo.ProductTableType READONLY)
    AS
    BEGIN
        SELECT CAST(1 AS bit) AS Result
        WHERE (SELECT COUNT(DISTINCT ProductID) FROM @param)
            = (SELECT COUNT(DISTINCT p.ProductID) FROM @param AS p
               INNER JOIN Products 
                   ON p.ProductID = Products.ProductID)
    END
    

    I changed this to return a row, as you seem to require. There are other ways to do this with a WHERE NOT EXISTS (LEFT JOIN in here WHERE rhs IS NULL):

    CREATE PROCEDURE usp_CheckAll 
        (@param dbo.ProductTableType READONLY)
    AS
    BEGIN
        SELECT CAST(1 AS bit) AS Result
        WHERE NOT EXISTS (
            SELECT * FROM @param AS p
            LEFT JOIN Products 
                ON p.ProductID = Products.ProductID
            WHERE Products.ProductID IS NULL
        )
    END
    

提交回复
热议问题