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

后端 未结 14 809
情深已故
情深已故 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条回答
  •  旧时难觅i
    2020-12-28 13:18

    Assuming you're using SQL Server, the boolean type doesn't exist, but the bit type does, which can hold only 0 or 1 where 0 represents False, and 1 represents True.

    I would go this way:

    select 1
        from Products
        where ProductId IN (1, 10, 100)
    

    Here, a null or no row will be returned (if no row exists).

    Or even:

    select case when EXISTS (
        select 1
            from Products
            where ProductId IN (1, 10, 100)
        ) then 1 else 0 end as [ProductExists]
    

    Here, either of the scalar values 1 or 0 will always be returned (if no row exists).

提交回复
热议问题