我想知道是否有可能这样做(这并不管用):

select cast((exists(select * from theTable where column like 'theValue%') as bit)

似乎它应该是可行的,但很多事情,应该在SQL中工作不;)我已经看到了这种变通方法(SELECT 1,其中…Exists…),但似乎我应该能够仅仅将Exists函数的结果转换为位,并完成它。


当前回答

我理解得有点晚了;只是无意中看到了这个帖子。然而,这里有一个比所选答案更有效和整洁的解决方案,但应该提供相同的功能:

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

其他回答

您还可以执行以下操作:

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

如果没有以“theValue”开头的值,将返回null(没有记录),而不是位0

SELECT IIF(EXISTS(SELECT * FROM theTable WHERE theColumn LIKE 'theValue%'), 1, 0)

不,这不可能。位数据类型不是布尔数据类型。整数数据类型,取值为0、1或NULL。

我理解得有点晚了;只是无意中看到了这个帖子。然而,这里有一个比所选答案更有效和整洁的解决方案,但应该提供相同的功能:

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

另一个解决方案是将ISNULL与SELECT TOP 1 1结合使用:

SELECT ISNULL((SELECT TOP 1 1 FROM theTable where theColumn like 'theValue%'), 0)