2010-05-11 39 views
2

我需要將表中的幾列連接成單個值,然後在asp下拉列表中顯示該值。我發出的SQL代碼如下:連接來自SQL查詢和NULL列的結果

SELECT用戶名,CustomerNum,用戶名+ ' - ' + UserAddress + '' + UserCity + '' + UserState AS的UserInfo 來自用戶的 WHERE(CustomerNum = @CustomerNum ) ORDER BY用戶名

然後,我將'UserInfo'設置爲下拉列表中的文本字段。

這通常起作用,除非偶爾在數據庫中有一列是空的(例如,UserState)。當發生這種情況時,整個串聯爲空,我在下拉列表中獲得一個空條目。

SQLServer中是否有某些東西可以讓我忽略這些NULL結果,還是必須在DataBind事件中編寫一些代碼?

謝謝

回答

1

對於可爲空的列做類似這樣的事情。

ISNULL(UserState, '') 
+0

謝謝 - 工作。 – Curtis 2010-05-11 15:23:52

0

你可以這樣做:

SELECT UserID, CustomerNum, UserName + ' - ' + 
    ISNULL(UserAddress + ',','') + ISNULL(UserCity,'') + ' ' + ISNULL(UserState,'') 
    AS UserInfo 
FROM Users 
WHERE (CustomerNum = @CustomerNum) ORDER BY UserName 
3

迴繞它凝聚

COALESCE(UserName,'') + ' - ' + 
COALESCE(UserAddress,'') + ',' + 
COALESCE(UserCity,'') + ' ' + 
COALESCE(UserState,'') AS UserInfo 
+1

合併是正確的方法。 – 2010-05-11 15:26:06

1

使用空連接來你的優勢,這將消除不必要的分隔符:

SELECT 
    UserID, CustomerNum 
     ,ISNULL(UserName+' - ','') 
      +ISNULL(UserAddress+', ','') 
      +ISNULL(UserCity+' ','') 
      +ISNULL(UserState,'') AS UserInfo 
    FROM Users 
    WHERE CustomerNum = @CustomerNum 
    ORDER BY UserName 

工作示例:

DECLARE @Users table (userID int, CustomerNum int,UserName varchar(20), UserAddress varchar(20), UserCity varchar(20), UserState varchar(20)) 
INSERT @Users VALUES (1,111,'Sam','123 First St.', 'city name', 'state name') 
INSERT @Users VALUES (2,111,null,'123 First St.', 'city name', 'state name') 
INSERT @Users VALUES (3,111,'Sam',null, 'city name', 'state name') 
INSERT @Users VALUES (4,111,'Sam','123 First St.', null, 'state name') 
INSERT @Users VALUES (5,111,'Sam','123 First St.', 'city name', null) 
INSERT @Users VALUES (6,111,null,null, 'city name', 'state name') 

SELECT 
    UserID, CustomerNum 
     ,ISNULL(UserName+' - ','') 
      +ISNULL(UserAddress+', ','') 
      +ISNULL(UserCity+' ','') 
      +ISNULL(UserState,'') AS UserInfo 
    FROM @Users 
    --WHERE CustomerNum = @CustomerNum 
    ORDER BY userID 

OUTPUT:

UserID  CustomerNum UserInfo 
----------- ----------- ------------------------------------------- 
1   111   Sam - 123 First St., city name state name 
2   111   123 First St., city name state name 
3   111   Sam - city name state name 
4   111   Sam - 123 First St., state name 
5   111   Sam - 123 First St., city name 
6   111   city name state name 

(6 row(s) affected) 
0

如果你想忽略空的結果(排除他們),你可以加我有什麼下面你WHEREISNULLCOALESCE可以用來爲空列選擇空字符串,如果這是你需要做的。

... 
WHERE UserName is not null 
AND UserAddress is not null 
AND UserCity is not null 
AND UserState is not null 
2

對於SQL Server,你有三種選擇:

  1. ISNULL - 這是最古老和最兼容的方法,但它並沒有在SQL Server精簡版存在(不知道這是否相關)。它接受兩個參數並返回非空的兩個參數中的第一個,如果兩個參數都返回null。
  2. 合併 - 這是新的開發更新,更喜歡。類似於IsNull,但可以採用兩個以上的參數。像IsNull一樣,它將返回第一個非空參數,如果全都是,則返回null。
  3. CONCAT_NULL_YIELDS_NULL - 這是一個數據庫選項,可以設置爲ONOFF。意思應該是自我解釋,但這是一個MSDN link