is it possible to select EXISTS directly as a bit?

后端 未结 9 1057
轻奢々
轻奢々 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:30

    You can use IIF and CAST

    SELECT CAST(IIF(EXISTS(SELECT * FROM theTable 
                           where theColumn like 'theValue%'), 1, 0) AS BIT)
    
    0 讨论(0)
  • 2020-12-02 09:36

    I believe exists can only be used in a where clause, so you'll have to do a workaround (or a subquery with exists as the where clause). I don't know if that counts as a workaround.

    What about this:

    create table table1 (col1   int null)
    go
    select 'no items',CONVERT(bit, (select COUNT(*) from table1) )   -- returns 'no items', 0
    go
    insert into table1 (col1) values (1)
    go
    select '1 item',CONVERT(bit, (select COUNT(*) from table1) )     --returns '1 item', 1
    go
    insert into table1 (col1) values (2)
    go
    select '2 items',CONVERT(bit, (select COUNT(*) from table1) )    --returns '2 items', 1
    go
    insert into table1 (col1) values (3)
    go
    drop table table1
    go
    
    0 讨论(0)
  • 2020-12-02 09:44
    SELECT IIF(EXISTS(SELECT * FROM theTable WHERE theColumn LIKE 'theValue%'), 1, 0)
    
    0 讨论(0)
提交回复
热议问题