is it possible to select EXISTS directly as a bit?

后端 未结 9 1056
轻奢々
轻奢々 2020-12-02 09:09

I was wondering if it\'s possible to do something like this (which doesn\'t work):

select cast( (exists(select * from theTable where theColumn like \'theValue

相关标签:
9条回答
  • 2020-12-02 09:18
    SELECT CAST(COUNT(*) AS bit) FROM MyTable WHERE theColumn like 'theValue%'
    

    When you cast to bit

    • 0 -> 0
    • everything else -> 1
    • And NULL -> NULL of course, but you can't get NULL with COUNT(*) without a GROUP BY

    bit maps directly to boolean in .net datatypes, even if it isn't really...

    This looks similar but gives no row (not zero) if no matches, so it's not the same

    SELECT TOP 1 CAST(NumberKeyCOlumn AS bit) FROM MyTable WHERE theColumn like 'theValue%'
    
    0 讨论(0)
  • 2020-12-02 09:24

    You can also do the following:

    SELECT DISTINCT 1
      FROM theTable
     WHERE theColumn LIKE 'theValue%'
    

    If there are no values starting with 'theValue' this will return null (no records) rather than a bit 0 though

    0 讨论(0)
  • 2020-12-02 09:25

    No, you'll have to use a workaround.

    If you must return a conditional bit 0/1 another way is to:

    SELECT CAST(
       CASE WHEN EXISTS(SELECT * FROM theTable where theColumn like 'theValue%') THEN 1 
       ELSE 0 
       END 
    AS BIT)
    

    Or without the cast:

    SELECT
       CASE
           WHEN EXISTS( SELECT 1 FROM theTable WHERE theColumn LIKE 'theValue%' )
                THEN 1 
           ELSE 0 
       END
    
    0 讨论(0)
  • 2020-12-02 09:26

    Another solution is to use ISNULL in tandem with SELECT TOP 1 1:

    SELECT ISNULL((SELECT TOP 1 1 FROM theTable where theColumn like 'theValue%'), 0)
    
    0 讨论(0)
  • 2020-12-02 09:28

    No it isn't possible. The bit data type is not a boolean data type. It is an integer data type that can be 0,1, or NULL.

    0 讨论(0)
  • 2020-12-02 09:30

    I'm a bit late on the uptake for this; just stumbled across the post. However here's a solution which is more efficient & neat than the selected answer, but should give the same functionality:

    declare @t table (name nvarchar(16))
    declare @b bit
    
    insert @t select N'Simon Byorg' union select N'Roe Bott'
    
    
    select @b = isnull((select top 1 1 from @t where name = N'Simon Byorg'),0)
    select @b whenTrue
    
    select @b = isnull((select top 1 1 from @t where name = N'Anne Droid'),0)
    select @b whenFalse
    
    0 讨论(0)
提交回复
热议问题