Tuesday, 20 August 2013

Converting NULL values to "UNKNOWN" without knowing column type

Converting NULL values to "UNKNOWN" without knowing column type

I've got several databases that I'm trying to query on my website with the
same SQL code. I'm passing the column names/table that I'd like to use via
URL to a new page. For example:
/some/url.php?table=tableName&c1=ColumnOne&c2=ColumnTwo&c3=ColumnThree&n=3
I have several of these URLs that all link to the same page (but with
different table names and columns). On the next page, the PHP code would
be something like this
for ($j = 1; $j <= $n; $j++) {
// Since the number of column variables varies (there could be c1 and
c2, or c1 -> c5), you need to save this part of the query in a
variable
$variables .= ${'c' . $j} . ', ';
}
SELECT $variables
FROM db.dbo.tableName
So the actual query for these 3 columns would be
SELECT ColumnOne, ColumnTwo, ColumnThree
FROM db.dbo.tableName
The problem is that some of the columns are float and some are
nvarchar(254). In the float columns, the null values are 0. In the
nvarchar(254) columns, null values are just NULL. I need the NULL values
in nvarchar(254) columns to be "UNKNOWN", and the 0 values in float
columns to also be "UNKNOWN".
This is an example of what I mean. ColumnOne and ColumnTwo are float,
while ColumnThree is nvarchar(254).
---------------------------------------------
|ColumnOne |ColumnTwo |ColumnThree |
---------------------------------------------
|0 |142563 |Insert |
---------------------------------------------
|1 |348 |Some |
---------------------------------------------
|2 |2535 |NULL |
---------------------------------------------
|3 |0 |Value |
---------------------------------------------
|0 |82536 |NULL |
---------------------------------------------
|5 |0 |Here |
---------------------------------------------
Here is what I would like it to look like
---------------------------------------------
|ColumnOne |ColumnTwo |ColumnThree |
---------------------------------------------
|UNKNOWN |142563 |Insert |
---------------------------------------------
|1 |348 |Some |
---------------------------------------------
|2 |2535 |UNKNOWN |
---------------------------------------------
|3 |UNKNOWN |Value |
---------------------------------------------
|UNKNOWN |82536 |UNKNOWN |
---------------------------------------------
|5 |UNKNOWN |Here |
---------------------------------------------
I've tried this
SELECT ISNULL(ColumnOne, 'UNKNOWN'), ISNULL(ColumnTwo, 'UNKNOWN'),
ISNULL(ColumnThree, 'UNKNOWN')
FROM db.dbo.tableName
However, I'm getting this error: Error converting data type varchar to float
Can someone help me out? It would be greatly appreciated!

No comments:

Post a Comment