How to convert the below SQL query to work in snowflake? - sql

SELECT
LEFT(Replace([SERIAL_NBR],'"',''),34) AS [SERIAL_NBR]
,CONVERT(datetime, Replace([INSERTED_DTM],'"',''), 103) AS [INSERTED_DTM]
,LEFT(Replace([GROUP_NAME],'"',''),1024)
,LEFT(Replace([FIRST_NAME],'"',''),50)
,LEFT(Replace([LAST_NAME],'"',''),50)
,LEFT(Replace([REASON_CODE_ID],'"',''),30)
,CASE isnumeric(Replace([VALUE],'"',''))
when 1
then CAST(Replace([VALUE],'"','') AS float)
else null
END AS [VALUE]
,LEFT(Replace([AUTOLOAD_DELIVERY_STATE_ID],'"',''),15)
,LEFT(Replace([RIDER_CLASS],'"',''), 20)
,LEFT(Replace([ADJUSTMENT_NOTES],'"',''), 1024)
FROM X
This is what I changed it to
SELECT
LEFT(Replace(SERIAL_NBR,'"',''),34) AS SERIAL_NBR
,to_timestamp(Replace(INSERTED_DTM,'"',''), 'DD/MM/YYYY') AS INSERTED_DTM
,LEFT(Replace(GROUP_NAME,'"',''),1024)
,LEFT(Replace(FIRST_NAME,'"',''),50)
,LEFT(Replace(LAST_NAME,'"',''),50)
,LEFT(Replace(REASON_CODE_ID,'"',''),30)
,CASE
WHEN is_Double(Replace(VALUE,'"','')) = 1
THEN CAST(Replace(VALUE,'"','') AS NUMBER)
ELSE NULL
END AS VALUE
,LEFT(Replace(AUTOLOAD_DELIVERY_STATE_ID,'"',''),15)
,LEFT(Replace(RIDER_CLASS,'"',''), 20)
,LEFT(Replace(ADJUSTMENT_NOTES,'"',''), 1024)
FROM stage."TL_A2_Adjustment_Note"
WHERE Replace(SERIAL_NBR,'"','') != 'A2'
It's giving me the error
001044 (42P13): SQL compilation error: error line 9 at position 9
At WHEN is_Double(Replace(VALUE,'"','')) = 1

The case statement is saying "when it can be parsed as a double/numeric do so, else use NULL"
Thus is snowflake this section:
,CASE
WHEN is_Double(Replace(VALUE,'"','')) = 1
THEN CAST(Replace(VALUE,'"','') AS NUMBER)
ELSE NULL
END AS VALUE
can use TRY_TO_DOUBLE which if it fails to parse as a float, will return null.
thus:
,TRY_TO_DOUBLE(Replace(VALUE,'"','')) as value

Related

I need help defining a case statement in SQL db2-400

I am using SQL, IBM Data Studio, db2-400. I need help writing a case statement that looks for the length of a field and returns a blank if it is not equal to 14, I have tried many ways without success, below is my latest attempt.
CASE
WHEN LENGTH(TRIM(FFIUPCN) <> '14'
THEN ''
ELSE
FFIUPCN
END AS "UPC (if applicable)"
The error I get is that the token "<>" is not valid.
Main issue is that you are missing a )
CASE
WHEN LENGTH(TRIM(FFIUPCN)) <> 14
THEN ''
ELSE
FFIUPCN
END AS "UPC (if applicable)"
but you shouldn't be comparing a numeric, returned by length(), to a sring '14'. But Db2 is implicitly converting it.
For multiple conditions you can nest your case statements
Select
case when FIUPCN+FFIUPCN2 = 0
then case when FIUPCN >= value then FIUPCN + 1
else FIUPCN + 2 end
else
case when FIUPCN >= value
then case when FIUPCN <> ''
then FIUPCN + 3
else prvca1 end
else
case
when FIUPCN >= FIUPCN2 and FIUPCN3 <> 0 then FIUPCN + 4
when FIUPCN >= FIUPCNX and FIUPCNY <> 0 then FIUPCN + 5
else prvca1 end
end
end
from table

SQL - want to write unique error value per IF condition

I'm handing lots of data and error checking it to ensure that it follows a correct format. So I'm creating a lot of IF conditions and so far I can group lots of conditions but only output one kind of error .. or i end up writing a heck of a lot of code per condition, just to have a crystal clear error output.
Is there a way to put into the IF condition a specific error output string?
Here is my code:
-- set the initial #IntHosp_SUM value
SELECT #IntHosp_SUM = 0
-- Store the sum value to #IntHosp_SUM
SELECT #IntHosp_SUM =
(
(COALESCE (CASE WHEN #Int1_5hosp = 1 THEN COUNT (Int1_5) ELSE NULL END, 0)) +
(COALESCE (CASE WHEN #Int2_5hosp = 1 THEN COUNT (Int2_5) ELSE NULL END, 0)) +
(COALESCE (CASE WHEN #Int3_5hosp = 1 THEN COUNT (Int3_5) ELSE NULL END, 0)) +
(COALESCE (CASE WHEN #Int4_5hosp = 1 THEN COUNT (Int4_5) ELSE NULL END, 0)) +
(COALESCE (CASE WHEN #Int5_5hosp = 1 THEN COUNT (Int5_5) ELSE NULL END, 0)) +
(COALESCE (CASE WHEN #Int6_5hosp = 1 THEN COUNT (Int6_5) ELSE NULL END, 0))
)
FROM ASSSIST2_M0Teacher
-- Check RESUSE_SUM Value against Intervention Entries
SELECT #ErrorID = IsNull(Max(ErrorID) + 1, 1)
FROM ErrorTemp
WHERE (Quest = #DB + #Quest) AND (ValidateID = #ValidateID)
SELECT #Error = 0
IF (#IntHosp_SUM = 1 and #Hosp1_info is null )
or (#IntHosp_SUM = 2 and (#Hosp1_info is null or #Hosp2_info is null))
or (#IntHosp_SUM >=3 and (#Hosp1_info is null or #Hosp2_info is null or #Hosp3_info is null))
or (#IntHosp_SUM = 0 and (#Hosp1_info is not null or #Hosp2_info is not null or #Hosp3_info is not null ))
or (#IntHosp_SUM = 1 and (#Hosp2_info is not null or #Hosp3_info is not null ))
or (#IntHosp_SUM >= 2 and #Hosp3_info is not null)
BEGIN
SELECT #Error = 1
END
BEGIN
IF #Error = 1
INSERT INTO ErrorTemp
(Quest,
ValidateID,
ErrorID,
ErrorType,
ErrorDesc,
Field)
VALUES (#DB + #Quest,
#ValidateID,
#ErrorID,
'Validation',
'Too much or no info present, so incorrect',
'Hosp Info - admissions')
SELECT #ErrorID = #ErrorID + 1
END
I have declared all variables and where they are in the DB, but didn't want to clutter with extra code. You can see that I sum a series of fields if they contain the value 1 .. I don't want to add any other values, just those with '1'.
My IF conditions then check if that if there is a sum of 1, there is one entry. If 2, then two entries .. we have to be thorough and check the inverse of that, so if the sum value is 0, then no entries are made and so forth.
Is there a way to pass a string from the IF / OR condition to the error output so that I can write a unique error per condition?
SQL Server Management Studio 17.2

CASE statement giving wrong results inside my stored procedure

I have a case inside my stored procedure which I use before executing the data.
DECLARE #Setup nvarchar(50)
SELECT
#ZipCode = CASE
WHEN REPLACE(#ZipCode, '0', '') = ''
THEN NULL ELSE #ZipCode
END,
#ZipCodeEND = CASE
WHEN REPLACE(#ZipCodeEND, '0', '') = ''
THEN NULL ELSE #ZipCodeEND
END,
SELECT
#Setup = CASE WHEN (LEN(ISNULL(#ZipCode, ''))) > 0 THEN '1' ELSE '0' END +
CASE WHEN (LEN(ISNULL(#ZipCodeEND,''))) > 0 THEN '1' ELSE '0' END
IF ISNULL(#ID, 0) = 0
BEGIN
INSERT INTO dbo.MapToStaticValuesTable(ZipCode, ZipCodeEND, Setup)
VALUES(#ZipCode, #ZipCodeEND, #Setup)
END
The problem here is even if zipcode and zipcodeEnd are empty and set to null after being saved into the table I keep getting the value "11" instead of getting "00".
Now if I do the same example with nvarchar values it would work, but since ZipCode and ZipCodeEnd are set to int it's acting weird.
It is acting weird because you are using string functions on integers. Not sure what you are trying to achieve with your code but I'm sure it can be done just by checking the values as integers.
I guess this could be what you are looking for.
select case when nullif(#ZipCode, 0) is null then '0' else '1' end +
case when nullif(#ZipCodeEND, 0) is null then '0' else '1' end
One example of weird
select isNull(#ZipCode, '')
return 0 if #ZipCode is null.

Conversion failed when converting the varchar value to data type bit in sql server

Here i try to convert a bit value to varchar , i try this query in MS sql server
CASE WHEN cast(ISNULL(O.isTerminated,0)as varchar) = 1 THEN 'Yes' ELSE '' END AS isTerminated.
Is giving error "Conversion failed when converting the varchar value 'Yes' to data type bit."
what will be the solution for this.
The error is not caused by the statement you are showing but by what you do with your isTerminated alias afterwards.
Your statement as is doesn't throw any errors.
DECLARE #isTerminated BIT = 1
SELECT CASE WHEN CAST(ISNULL(#isTerminated, 0) AS VARCHAR) = 1
THEN 'yes'
ELSE ''
END AS isTerminated
But treating the aliased isTerminated as a bit does.
DECLARE #isTerminated BIT = 1
SELECT *
FROM (SELECT CASE WHEN CAST(ISNULL(#isTerminated, 0) AS VARCHAR) = 1
THEN 'yes'
ELSE ''
END AS isTerminated) t
WHERE isTerminated = 1 -- isTerminated is a VARCHAR at this point
Why are you casting the bit to a varchar. Can you just do this:
CASE WHEN ISNULL(O.isTerminated,0) = 1 THEN 'Yes' ELSE '' END AS isTerminated
EDIT
When trying this example.
DECLARE #T TABLE(isTerminated BIT)
INSERT INTO #T
VALUES(1),(NULL),(0)
SELECT
CASE WHEN ISNULL(O.isTerminated,0) = 1 THEN 'Yes' ELSE '' END AS isTerminated
FROM
#T AS O
With your case statement. I don't revise a error. Are you missing out any details?

if statement in sql server

i am getting the following error:
Incorrect syntax near 'cast', expected 'AS'.
on this line:
use SalesDWH
go
if (select isnumeric(result))=1
begin
select max(cast(result) as decimal(10,2)) from testresults
end
testresults table contains about 21 million rows of data.
what am i doing wrong? thanks so much.
thank you everyone for you rhelp.
i've changed the code to:
use SalesDWH
go
if (select isnumeric(result))=1
begin
select max(cast(result as decimal(10,2))) from testresults
end
and now i am getting error:
Msg 207, Level 16, State 1, Line 1
Invalid column name 'result'.
it's definitely a valid column
i took kris' suggestion and did this:
use SalesDWH
go
SELECT MAX( CAST( [Result] AS DECIMAL(9,2) ) )
FROM [testresults]
WHERE ISNUMERIC( [Result] ) = 1
and dbo.isReallyNumeric([Result]) = 1
and dbo.isReallyInteger([Result]) = 1
the functions are here http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html
and the result that i got was NULL!!!!!
i need a numeric result. what am i doing wrong?
here is a sample of the data:
625857 AMPH-AMPHETAMINES 357.1 EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625858 AMP_C-Amphetamine NEGATIVE EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625859 BARB-BARBITURATES 7.1 EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625860 BENZ-BENZODIAZEPINES 1.2 EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625861 COCN-COCAINE METABOLITES -105.5 EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625862 CR-CREATININE (CHEMICAL) 57.8 EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625863 ETOH-ETHANOL 134.5 EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625864 METAMP_C-Methamphetamine NEGATIVE EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
625865 METD-METHADONE -32.3 EBB74CF9-D12D-4FBC-917F-91D9DAC169F3
thank you for all your help. i think i am getting closer:
select MAX(cast(char_value as decimal(10,2))) from
(SELECT
Char_Number = CASE
WHEN id <= 255 THEN RTRIM(id)
ELSE '-' END,
Char_Value = RTRIM(CASE
WHEN id <= 255 THEN CHAR(id)
ELSE result END),
is_numeric = ISNUMERIC(result),
is_really_numeric = dbo.isReallyNumeric(result),
is_really_integer = dbo.isReallyInteger(result)
FROM
testresults
WHERE
ISNUMERIC(result) = 1
OR dbo.isReallyNumeric(result) = 1
OR dbo.isReallyInteger(result) = 1
)
where is_really_numeric=1
but i am getting this error:
Msg 156, Level 15, State 1, Line 20
Incorrect syntax near the keyword 'where'.
updated based on guess of what you were looking for
SELECT MAX( CAST( [Result] AS DECIMAL(10,2) ) )
FROM [testresults]
WHERE ISNUMERIC( [Result] ) = 1;
Try this one
use SalesDWH
go
SELECT MAX(CAST(Result AS DECIMAL(10,2))) FROM testresults WHERE isnumeric(result)=1
But if you get NULL as a result even with this:
and dbo.isReallyNumeric([Result]) = 1
and dbo.isReallyInteger([Result]) = 1
then this may be the actual result - there is no any numberic values in the column
OR
the really numberic values of column are left- or right-padded with spaces etc...
OR
you stripe all the floats with this dbo.isReallyInteger([Result]) = 1 and you have no pure integers in the table
If you are still getting the error, just give an alias to your inner table.
select MAX(cast(char_value as decimal(10,2))) from
(SELECT
Char_Number = CASE
WHEN id <= 255 THEN RTRIM(id)
ELSE '-' END,
Char_Value = RTRIM(CASE
WHEN id <= 255 THEN CHAR(id)
ELSE result END),
is_numeric = ISNUMERIC(result),
is_really_numeric = dbo.isReallyNumeric(result),
is_really_integer = dbo.isReallyInteger(result)
FROM
testresults
WHERE
ISNUMERIC(result) = 1
OR dbo.isReallyNumeric(result) = 1
OR dbo.isReallyInteger(result) = 1
) myInnerTable
where is_really_numeric=1