use cast in SQL case statement - sql

SELECT
CASE
WHEN column1 = 43 THEN CAST('abcde' as varchar(30))
WHEN column1 = 44 THEN CAST('fghij' as varchar(30))
ELSE 'N/A'
END AS value
Is the above case and cast statement correct? I need to convert the int to a varchar. column1 is a value that comes from another table.
Question 2: I have two values coming from two different tables (table1 and table2) and they need to go to the final table data type varchar
value 1 = CONVERT(VARCHAR(10),CAST(c.table1 * 100 AS DECIMAL(5,2))) + ' %' AS value1
value 2 = CONVERT(VARCHAR(10),c.table2,101) AS value2
c.table1 is decimal coming from table1
c.table2 is int coming from table2 and both need to be varchar at the final table
how do I combine both statements so that it can show up in the final table, its not an OR its an AND.
result set:

Related

Coalesce in where clause with n

I am trying to get records based on the given input values. Below is the sample script
DECLARE input1 = '001'
DECLARE input2 = '002'
SELECT * FROM table WHERE COLUMN1 = COALESCE(input, NULL) OR
COLUMN2 = COALESCE(input2, NULL)// return non-null records, Great
DECLARE input1 = NULL
DECLARE input2 = NULL
SELECT * FROM table WHERE COLUMN = COALESCE(input, NULL) // return no records, Problem here
I know, COLUMN = NULL do not yield any values. Is there a better way, so that NULL input values return null records. Thanks in advance.
A "better" option might be to skip COALESCE (or NVL) and switch to
where column = input
or (column is null and input is null)
Your query:
SELECT *
FROM table
WHERE COLUMN1 = COALESCE(input, NULL)
OR COLUMN2 = COALESCE(input2, NULL)
Will only return results when COLUMN1 = input OR column2 = input. It will not return results when both columns are NULL.
You will get exactly the same results if you remove the COALESCE expressions:
SELECT *
FROM table
WHERE COLUMN1 = input
OR COLUMN2 = input2
If you want to check when the input is NULL and the column value is also NULL then you need to use IS to compare the values to NULL and not = like this:
SELECT *
FROM table
WHERE COLUMN1 = input -- Compare non-NULL values
OR ( input IS NULL AND COLUMN1 IS NULL ) -- Compare NULL values
OR COLUMN2 = input2 -- Compare non-NULL values
OR ( input2 IS NULL AND COLUMN2 IS NULL ) -- Compare NULL values
If you need to return rows with COLUMN1 is NULL in case of INPUT is null:
SELECT *
FROM table
WHERE
decode(COLUMN1,input, 1,0) = 1
Decode: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/DECODE.html#GUID-39341D91-3442-4730-BD34-D3CF5D4701CE
In a DECODE function, Oracle considers two nulls to be equivalent
You do not need coalesce in this query from your question:
SELECT *
FROM table
WHERE COLUMN1 = COALESCE(input, NULL) OR
COLUMN2 = COALESCE(input2, NULL)
because coalesce(input,null) is equal to simple input: coalesce returns first non-null parameter, but your second parameter is null, so it returns
input is not NULL | input
-------------------------
input is NULL | null

Conversion Failed Nvarchar to INT

I have two tables called Entry_Data and Data
Entry_Data has three columns:
EntryID DataID DataTypeID
1       50      18
2       49       59
30      28      16
Data has two columns:
DataID Value
50      0x00000000033654
49      Removable
28      E:\Test.txt
The Value column is an nvarchar field.
I have written a left join while attempting to convert all Value fields that start with 0x to an int so that the Hexadecimal value can be converted into a meaningful and human readable value however I get the error:
Conversion failed when converting the nvarchar value
‘0x00000000033654’ to data type int
SELECT TOP 100
Entry_Data.DataTypeID AS DataTypeID,
CAST(Data.Value AS nvarchar(440)) AS Value,
Data.DataID AS DataID
FROM ActivityLog.Entry_Data
LEFT JOIN ActivityLog.Data
ON ActivityLog.Entry_Data.DataID =
CASE
WHEN DataTypeID = 18 AND
Value LIKE '%0x%' THEN CONVERT(nvarchar, CONVERT(int, Value, 1))
ELSE DataTypeID
END
WHERE DataTypeID = 18
In your case expression, you are returning an nvarchar for one situation
THEN CONVERT(nvarchar, CONVERT(int, Value, 1))
and an integer for the second situation
ELSE DataTypeID
You need to correct your join so it always return and int for the join to work.

Convert INT column values to an empty string using ISNULL

I need to convert column ID of INT data type to a empty string ['']. I should not modify the source column data type, but need to convert it in my transformation in the other table. The ID column is "nullable" as it has null in it.This is my code.
CREATE TABLE #V(ID INT) ;
INSERT INTO #V
VALUES (1),(2),(3),(4),(5),(NULL),(NULL) ;
SELECT CASE WHEN CAST(ISNULL(ID,'') AS VARCHAR(10)) = '' THEN '' ELSE ID END AS ID_Column
FROM #V;
this returns:
ID_Column
1
2
3
4
5
NULL
NULL
when I modify my CASE statement it as follows:
CASE WHEN CAST(ISNULL(ID,'') AS VARCHAR(10)) = '' THEN '' ELSE ID END AS ID_Column
it returns:
ID_Column
1
2
3
4
5
0
0
Is this what you want?
select coalesce(cast(id as varchar(255)), '')
from #v;
You have to turn the entire result column into a single column. If you want a blank value, then the type is some sort of character string.
In your examples, the else id means that the result from the case is an integer, which is why you are getting either 0 or NULL.

SQL Server: Compare two columns

I have two columns in a SQL table as follow. I need to compare these two columns for mismatches but due to extra decimals i am getting false results. When i try to convert the first column it gives the error
"Error converting data type varchar to numeric."
How to solve this issue? The length of first column varies.
Column01(varchar) Column02(Decimal)
0.01 0.010000
0.255 0.255000
You have data in Column01 that cannot be casted to DECIMAL.
With SQL Server 2012+ I would use TRY_PARSE:
SELECT *
FROM your_table
WHERE Column02 = TRY_PARSE(Column01 AS DECIMAL(38,18));
LiveDemo
When value from column cannot be casted safely you get NULL.
For SQL Server 2008 you can use:
SELECT *
FROM #tab
WHERE (CASE
WHEN ISNUMERIC(Column01) = 1 THEN CAST(Column01 AS DECIMAL(38,18))
ELSE NULL
END) = Column02;
EDIT:
If you need it at column level use:
SELECT Column01, Column02,
CASE WHEN Column02 = TRY_PARSE(Column01 AS DECIMAL(38,18))
OR (Column02 IS NULL AND Column01 IS NULL)
THEN 'true'
ELSE 'false'
END AS [IsEqual]
FROM #tab;
LiveDemo2
You can do this using self join and conversion function
SELECT x.Column01, y.Column02
FROM table1 x, table1 y
WHERE x.Column02 = try_parse(y.Column01 as decimal(38,18))
Since I cannot comment, I like to thank lad2025 for showing live demo and introducing to data.stackexchange for composing queries
One other way of doing it:
create table #temp(col1 varchar(10),col2 decimal(10,6))
insert into #temp values(0.01,0.010000 ),(0.255,0.255000),(0.25,25),(0.555,10.0)
select * from #temp where REPLACE(REPLACE(col2,col1,''),0,'') = ''
select * from #temp where REPLACE(REPLACE(col2,col1,''),0,'') <> ''

SQL select with 'in' casting from string to tinyint

I have a table from which I want to select data. One coloumn 'myCol' has datatype tinyint. It has values from 1 to 8.
In my select I have a variable #myVar with datatype varchar(), that has values like '1,2' or '3,4'.
Now I am trying to do something like this:
select * from myTable
where myCol in (#myVar)
Unfortunately I get the following error:
Conversion failed when converting the varchar value '2,3' to data type tinyint.
How to change the select that it works like it should?!
It's very important to keep the select performance as high as possible!
Since you only have values from 1 to 8 you can use a string search method. Something like
select * from myTable
where CHARINDEX(cast(mycol as varchar), #myVar) > 0
SQLFiddle demo
If you create a function similar to the accepted answer in Splitting of comma separated values, you will then be able to do:
select * from myTable t
inner join dbo.fnSplitStringAsTable(#myVar, ',') s on t.myCol = s.Value
Note that I'm assuming SQL Server, based on your syntax and the error message.
Change your data to contain flagged enum
[Flags]
public enum ContactMethod
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
Value4 = 8,
Value5 = 16,
Value6 = 32,
Value7 = 64,
Value8 = 128
}
select * from mytable where myCol | 3 = 3
Will then return you all rows with values 1 or 2