简体   繁体   中英

SQL — Assigning a bit variable in select statement

For example:

declare @bitHaveRows bit
 select @bitHaveRows = count(*)
   from table
  where (predicate)

Are there any functions I can call on this line:

select @bitHaveRows = count(*)

to assign this bit a value of 0 if there are no rows, or 1 if there are one or more rows?

declare @bRowsExist
SELECT @bRowsExist = CAST(count(*) as bit)
FROM yourtable

...not sure if it's a better query than the other suggestions

According to the c onversion chart , there's an implicit conversion from int to bit. But if for some reason that doesn't work:

CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END

If your database supports it, you can use a CASE statement:

declare @bitHaveRows
select @bitHaveRows = case when count(*) > 0 then 1 else 0 end
from yourtable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM