2014-03-31 311 views
0
select COALESCE([ItemSlotX],0) as [ItemSlotX],COALESCE([ItemSlotY], 0) as [ItemSlotY] from [PowerUP_Items] where [ItemIndex]=16 and [ItemGroup]=255 

在我的情況下,沒有記錄。MSSQL返回0爲空白

如果沒有找到記錄,如何返回ItemSlotX的0和ItemSlotY的0?

+0

什麼數據類型是ItemSlotX和ItemSlotY? – dean

+0

當你說空白\空你的意思是你沒有回行嗎? – sarin

+0

列的數據類型爲int。 – MeTa

回答

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 
+0

我知道結果,但我的問題是:如果此查詢有結果(沒有記錄/空)我怎麼可以告訴sql來返回我在這兩個領域0。 – MeTa

+0

太棒了!就是這個!非常感謝你! – MeTa

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 
+0

一般的做法很好,謝謝! – MeTa

0

如果您的查詢必須返回不超過一行,請嘗試這個

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