MSSQL返回0表示空白

时间:2014-03-31 10:31:02

标签: sql sql-server

select COALESCE([ItemSlotX],0) as [ItemSlotX],COALESCE([ItemSlotY], 0 ) as [ItemSlotY] from [PowerUP_Items] where [ItemIndex]=16 and [ItemGroup]=255

在我的情况下,没有记录。

如果没有找到记录,如何为ItemSlotX返回0,为ItemSlotY返回0?

3 个答案:

答案 0 :(得分:1)

如果您想要结果,即使没有匹配的行,也请使用:

select COALESCE([ItemSlotX],0) as [ItemSlotX],COALESCE([ItemSlotY], 0 ) as [ItemSlotY]
from (select null dummy ) d
left
outer
join [PowerUP_Items]
on   [ItemIndex]=16 and [ItemGroup]=255

答案 1 :(得分:1)

此?

select ItemSlotX, ItemSlotY from PowerUP_Items where ItemIndex=16 and ItemGroup=255
if @@rowcount = 0
    select 0 as ItemSlotX, 0 as ItemSlotY 

或更一般的方法:

if exists (select * from PowerUP_Items where ItemIndex=16 and ItemGroup=255)
    select ItemSlotX, ItemSlotY from PowerUP_Items where ItemIndex=16 and ItemGroup=255
else
    select 0 as ItemSlotX, 0 as ItemSlotY 

答案 2 :(得分:0)

如果您的查询必须返回不超过一行,请尝试此

select COALESCE(max([ItemSlotX]),0) as [ItemSlotX],COALESCE(max([ItemSlotY]), 0 ) as [ItemSlotY] 
from [PowerUP_Items] where [ItemIndex]=16 and [ItemGroup]=255