如:
select num1 from biao1 where 条件
其中NUM1为decimal型,按条件查询不出这行,有就是数据库中没有符合条件的行,什么也查不出来,但是在这种情况下我想查询出的直为0,怎么写?PS:select isnull(num1,0) from biao1 where 条件 不能实现
select num1 from biao1 where 条件
其中NUM1为decimal型,按条件查询不出这行,有就是数据库中没有符合条件的行,什么也查不出来,但是在这种情况下我想查询出的直为0,怎么写?PS:select isnull(num1,0) from biao1 where 条件 不能实现
select num=isnull(select num1 from biao1 where 条件),0)
select isnull(num1,0) as num1 from biao1 where 条件
SELECT CASE WHEN NOT EXISTS(select 1 from biao1 where 条件) THEN 0 ELSE NUM1 END AS NUM1 FROM BIAO1
楼主的select isnull(num1,0) from biao1 where是判断num1是不是null,而不是查询结果有没有。
select @num1=num1 from biao1 where 条件
if @@rowcout>0
begin
select @num1
end
else
begin
select 0
end
其中NUM1为decimal型,按条件查询不出这行,有就是数据库中没有符合条件的行,
什么也查不出来,但是在这种情况下我想查询出的直为0,怎么写?PS:select isnull(num1,0) from biao1 where 条件 不能实现
*/
--方式1
select case when not exists(select num1 from biao1 where 条件) then 0 end -->举例:
select case when exists (select num1 from (select 1 num1,'a' a union all select null,'b') b where a='b')
then 0 end
--方式2
select cast(isnull(num1,0) as int) from biao1 where 条件 可以实现--举例:
select cast(isnull(num1,0) as int) num1
from (
select 1.11 num1,'a' a union all
select null,'b') b
where a='b'
select case when not exists(select num1 from biao1 where 条件) then 0 end -->举例:
select case when exists (select num1 from (select 1 num1,'a' a union all select null,'b') b where a='b')
then 0 end
--方式2
select cast(isnull(num1,0) as int) from biao1 where 条件 可以实现--举例:
select cast(isnull(num1,0) as int) num1
from (
select 1.11 num1,'a' a union all
select null,'b') b
where a='b
select case when not exists(select num1 from biao1 where 条件) then 0 end -->举例:
select case when exists (select num1 from (select 1 num1,'a' a union all select null,'b') b where a='b')
then 0 end
--方式2
select cast(isnull(num1,0) as int) from biao1 where 条件 可以实现--举例:
select cast(isnull(num1,0) as int) num1
from (
select 1.11 num1,'a' a union all
select null,'b') b
where a='b
这种情况只是考虑了没有结果的情况,要是有条件满足的记录集大于1 行,就不对了,会出现如下报错:
服务器: 消息 512,级别 16,状态 1,行 16
子查询返回的值多于一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
所以,if exists(select 1 from biao1 where 条件)
select num1 from biao1 where 条件
else
select 0 as num1
insert into @T(a,b)
select 1,12 union all
select 7,null union all
select 5,22.3 union all
select 2,16 union all
select 3,null union all
select 6,null union all
select 9,87.4select isnull(b,0) from @T where b is null