I need to concatenate several columns of a table into a single value, then show that value in an asp dropdownlist. The SQL code I'm issuing is as follows:
SELECT UserID, CustomerNum, UserName + ' - ' + UserAddress + ',' + UserCity + ' ' + UserState AS UserInfo FROM Users WHERE (CustomerNum = @CustomerNum) ORDER BY UserName
I then set 'UserInfo' as the text field in the dropdownlist.
This generally works, except occasionally one of the columns in the database is null (for example, UserState). When that happens, the entire concatenation is null, and I get an empty entry in the dropdownlist.
Is there something in SQLServer that will allow me to ignore those NULL results, or will I have to code something up in the DataBind event?
Thanks
For SQL Server, you have three choices:
IsNull
, but can take more than two arguments. LikeIsNull
, it will return the first non-null argument, or null if all are.ON
orOFF
. The meaning should be self-explanetory, but here's an MSDN link.Use the NULL concatenation to your advantage, this will remove unnecessary separator characters:
working example:
OUTPUT:
For the nullable columns do something like this.
If you want to ignore null results (exclude them) you can add what i have below to your
WHERE
.ISNULL
orCOALESCE
can be used to select empty strings for the null columns as described above if that's what you need to do.wrap coalesce around it
You can do this: