2012-10-08 69 views
0

我有一個沒有關係的表。當字段countyName是零長度字符串時,我需要Statewide在結果集中。否則,我需要將該字段的值保持原樣,例如:enter image description here請注意第二列中的'Statewide'和'countyName'。縣名應該是實際存儲在數據庫中的原始值。當SQL Server 2008的情況下

`countyName` `address` 
       blah blah 
Jackson  blah blah 

必須(在這兩個例子中第一行是列名)

countyName  address 
Statewide  blah blah 
Jackson  blah blah 

這裏是我試過了,可以忽略其餘字段在這個例子中

select case servicetype 
     when 'cr' then 'Community Resource' 
     when 'ed' then 'Education' 
     when 'fb' then 'Faith-based' 
     when 'me' then 'Medical Equipment' 
     when 'hc' then 'Health Care' 
     else 'Other' 
     end as serviceType 

     ,case countyName 
     when '' then 'Statewide' 
     else 'countyname' end 

     ,name 
     ,physicaladdress 
     ,city 
     ,statelocation 
     ,zip 
     ,phone 
     ,website 
     from main 

     order by countyName, servicetype, name 
+1

什麼是與您的查詢問題?你有什麼錯誤嗎?意外的結果? –

+0

查詢運行,但與第二個case語句,else不返回行中的原始值,一切都是'縣名' – wootscootinboogie

+0

@MahmoudGamal屏幕帽編輯。 – wootscootinboogie

回答

5

儘管沒有說究竟是什麼結果你希望,我猜測將是你不想要回文字「countyname」的。你想要的是列中的值。

因此,嘗試替換當前的case語句......

,case countyName 
when '' then 'Statewide' 
else countyName end 

作爲一個額外的安全網,您還可以檢查使用ISNULLNULL值...

,case ISNULL(countyName,'') 
when '' then 'Statewide' 
else countyName end 
+0

看起來不錯,接受它時會讓我感謝 – wootscootinboogie

+0

沒有問題@woot,很高興有幫助。祝好運與您的其餘項目 – freefaller

0

我想你正在尋找「IFNULL」功能。

簡單地使用這種方式:SELECT ...,ISNULL(column, "fallback value"),...你的情況

+0

它實際上是'ISNULL(....)'在T-SQL/SQL服務器 –

+1

supid me,marc_s是對的。逐漸老去並被所有的SQL衍生物所迷惑。 – Najzero

1

試試這個:

case when isnull(countyName,'') = '' then 'Statewide' else countyname end 
0

試試這個...... IsNULL應該被檢查。

case ISNULL(countyName,'') when '' then 'Statewide' else 'countyname' end

0
SELECT ProductNumber, Category = 
     CASE ProductLine 
     WHEN 'R' THEN 'Road' 
     WHEN 'M' THEN 'Mountain' 
     WHEN 'T' THEN 'Touring' 
     WHEN 'S' THEN 'Other sale items' 
     ELSE 'Not for sale' 
     END, 
    Name 
FROM Production.Product 
ORDER BY ProductNumber; 

GO

相關問題