SQL CASE with Alias - sql

I am trying to change a column name based on the results of a case statement, is this possible and how would I do it...here is what I have so far but I am not good enough at SQL yet.
I want the change the column name of VALUE to become NUMVALUE if the data is numeric and ALNVALUE if the data isn't numeric. Essentially making a three column datatable a four column datatable. Is this possible?
CASE WHEN ISNUMERIC([Value])=1 THEN SELECT [VALUE] AS [NUMVALUE] ELSE SELECT [VALUE] AS [ALNVALUE] END

No, it isn't possible.
Think about the issues you'd run into when you try and use the result set. Anytime you tried to access the data, you would get an exception stating that the column couldn't be found or similar.
Dim data = Results["ColumnName"] would become unreliable.
You will need to make a separate column for each of them or put them all under the same name.

You need two CASEs = two columns:
SELECT
CASE WHEN ISNUMERIC([Value])= 1 THEN [VALUE] END AS [NUMVALUE],
CASE WHEN ISNUMERIC([Value])<>1 THEN [VALUE] END AS [ALNVALUE],
...
FROM myTable

Related

SQL DB2 Replace value in a column

I have the following column, B represents boolean and the rest are empty values. I have to change all the values in this column to the word COLUMN A.
COLUMN
-----
B
I have tried different things, for example
SELECT COLUMN
FROM TABLE
WHERE COALESCE(NULLIF(COLUMN,''), 'COLUMN A');
And I receive the error: "Invalid character found in a character string argument of the function "BOOLEAN"." I'm kind of stuck to this question and I'm getting confused with this boolean value. I will be really happy if someone can help me, thanks!
The easiest thing is to use CASE expression. I am not familiar in db2, so you may want to research it further, but in other DBMSs it works like this:
SELECT CASE
WHEN COLUMN = '' THEN 'COLUMN A' -- if COLUMN = '', replace it with 'COLUMN A'
ELSE COLUMN -- otherwise, keep COLUMN as is.
END as 'COLUMN' -- name the column in the result 'COLUMN'
FROM TABLE
This is an article that explains how it works in db2:
https://www.ibm.com/support/knowledgecenter/en/SSEPEK_11.0.0/sqlref/src/tpc/db2z_caseexpression.html
The WHERE clause is unfinished. Compare the COALESCEd value to something:
SELECT COLUMN
FROM TABLE
WHERE COALESCE(NULLIF(COLUMN,''), 'COLUMN A') = 'COLUMN A';
Or better:
SELECT COLUMN
FROM TABLE
WHERE COLUMN IS NULL OR COLUMN = ''
Doesn't require any thinking/calculating to work out your selection logic. More maintainable, nicer for peer developers
*The above is generic advice for usual cases NOT involving boolean datatypes (which typically require some different treatment)
Now, you say you have to change the value to something. That requires an UPDATE statement. If this column is a boolean then it won't have a value of empty string. The blanks will be nulls:
UPDATE TABLE SET COLUMN = (some boolean) WHERE COLUMN IS NULL
If you don't want to permanently change the table data to something, but instead want to select it out as some value where a blank occurs, but keep the blanks stored in the table:
SELECT COALESCE(column, (some boolean)) FROM TABLE
Might be worth noting that not all versions of DB2 can return a boolean in a result set - this is quite typical of database vendors. Convert the boolean to something else representable using a case when, if your DB2 version is thus restricted
SELECT CASE WHEN column = TRUE THEN 'true' ELSE 'false' END FROM TABLE

TSQL Change column name in sql select statement based on parameter

Updating a stored procedure and want to be able to change the name of the column returned dependant on parameter input
I understand the below is not valid but thought it the best way to explain what I want to achieve.... I want to be able to change the name of the column in the select statement dependent on a input parameter...
(
CASE
WHEN (#DateExpired = 1) THEN sens.date1 AS [Expired]
ELSE sens.date1 AS [Due Date]
END
)
I can see how I could do this at whole table select level but did not want to duplicate code for the usual reasons associated with why duplicated code is bad. Any ideas appreciated!
Simply use an IF statement in your stored procedure...
IF #DateExpired = 1
SELECT sens.date1 AS Expired FROM sens
ELSE
SELECT sens.date1 AS [Due Date] FROM sens
If you are worried about the duplicate SQL (perhaps because your query is complex) then you could have your SQL statement insert your required data into a temporary table and then use the IF above replacing "sens" with your temp table and just return the column names from the temp table.
Hope that helps,
Ash
One way is to add both the columns in Select List and add a dummy date which is not feasible from application when condition are not met for that column like:
(
CASE WHEN (#DateExpired = 1) THEN sens.date1 ELSE '01-01-1900' END AS [Expired]
CASE WHEN (#DateExpired <> 1) THEN sens.date1 ELSE '01-01-1900' END AS [Due Date]
)
and then let the client application handle the invalid dates as required by the business..

SQL: What does NULL as ColumnName imply

I understand that AS is used to create an alias. Therefore, it makes sense to have one long name aliased as a shorter one. However, I am seeing a SQL query NULL as ColumnName
What does this imply?
SELECT *, NULL as aColumn
Aliasing can be used in a number of ways, not just to shorten a long column name.
In this case, your example means you're returning a column that always contains NULL, and it's alias/column name is aColumn.
Aliasing can also be used when you're using computed values, such as Column1 + Column2 AS Column3.
When unioning or joining datasets using a 'Null AS [ColumnA] is a quick way to make sure create a complete dataset that can then be updated later and a new column does not need to be created in any of the source tables.
In the statement result we have a column that has all NULL values. We can refer to that column using alias.
In your case the query selects all records from table, and each result record has additional column containing only NULL values. If we want to refer to this result set and to additional column in other place in the future, we should use alias.
It means that "aColumn" has only Null values. This column could be updated with actual values later but it's an empty one when selected.
---I'm not sure if you know about SSIS, but this mechanism is useful with SSIS to add variable value to the "empty" column.
When using SELECT you can pass a value to the column directly.
So something like :
SELECT ID, Name, 'None' AS Hobbies, 0 AS NumberOfPets, NULL AS Picture, '' AS Adress
Is valid.
It can be used to format nicely a query output when using UNION/UNION ALL.
Query result can have a new column that has all NULL values. In SQL Server we can do it like this
SELECT *, CAST(NULL AS <data-type>) AS as aColumn
e.g.
SELECT *, CAST(NULL AS BIGINT) AS as aColumn
How about without using the the as
SELECT ID
, Name
, 'None' AS Hobbies
, 0 AS NumberOfPets
, NULL Picture
Usually adding NULL as [Column] name at the end of a select all is used when inserting into another table a calculated column based on the table you have just selected.
UPDATE #TempTable SET aColumn = Column1 + Column2 WHERE ...
Then exporting or saving the results to another table.

How do I use case statement to aid altering another field?

I have a hopefully pretty simple question here. I'm converting some Access SQL script into Server Management Studio 2008.
Currently the Access script shows the following line of code:
IIf([rsosourceID]) IN (254,360,446),"MoneySavingExpert" as SourceName
Basically it's creating a temporary table with four columns, if the fields match say those 3 numbers on the left then it will populate a fourth column with their new name. (To be used for grouping in a later report)
How can I do something simillar in SQL? I've tried using a Case statement but to my knowledge that will only alter the field you're looking against.
In this case I need to look at one field then using it's results alter another, any ideas?
A case statement can return a new column using the value of any other column(s):
SELECT rsoSourceID,
rsoDescription,
rsoCategory,
case when rsoSourceID in (254,360,446)
then 'MoneySavingExpert'
else null end as SourceName
FROM TableName

What's wrong with my CASE?

CASE WHEN table1.text IS NULL THEN table2.numbers
ELSE table1.text
END AS newcolumn
When running this code I keep getting this error:
ERROR: CASE types character varying and integer cannot be matched
You would think that this would not cause problems since I'm creating a new column within my query. I'd also like to point out that I'm using an old version of PostgreSQL if that helps.
CASE WHEN table1.text IS NULL THEN table2.numbers::text ELSE table1.text END AS newcolumn
Problem is you are trying to add table1.text and table2.numbers into a single column. These two columns are two diff data types. try following
CASE WHEN table1.text IS NULL THEN CAST(table2.numbers AS VARCHAR(50)) ELSE table1.text END AS newcolumn
The data type represented by table2.numbers and table1.text has to be the same, so it looks like in this case you'll need to CAST the value of table2.numbers
Try ISNULL
CASE WHEN ISNULL(table1.text) = 1 THEN table2.numbers ELSE table1.text END AS newcolumn
I think the error is pretty clear - the types of the two columns that may be used by the CASE statement aren't compatible.
Why would you think that trying to use values from two columns of different types would not cause problems? You may be creating a new column in the result set, but it still has to have a type and that has to match all the potential values.
It may be possible in a lot of cases for it to infer the type, but that's risky and may not necessarily be the choice that you want it to make, so it's better for it to force you to make the decision. You'll need to modify the type of one or the other columns in the CASE statement.