Getting error trying to convert varchar to numeric - sql-server

How do I convert varchar to numeric. This is the code I use:
SELECT TOP 1000*
FROM [StorageDB - BAW].[dbo].[EMAIL_DETAILS_HOC] eh
LEFT JOIN [StorageDB - BAW].[dbo].[Customer_Details_201906] cd ON cd.CSTMR_NUM = CAST(eh.[CIS_NUMBER] AS NUMERIC(20,0))
I'm getting this error:
Error converting data type varchar to numeric

You may try using TRY_CONVERT to flush out offending records, assuming your version of SQL Server supports it:
SELECT [CIS_NUMBER]
FROM [StorageDB - BAW].[dbo].[EMAIL_DETAILS_HOC]
WHERE TRY_CONVERT(NUMERIC(20,0), [CIS_NUMBER]) IS NULL;

There are two possibilities for getting this error first is you have length issue or second you must have non numeric value in CIS_number field so check it. Then convert it accordingly.

You Can Use This Code and Test it.
SELECT TOP 1000 *
FROM [StorageDB - BAW].[dbo].[EMAIL_DETAILS_HOC] eh
LEFT JOIN StorageDB - BAW].[dbo].[Customer_Details_201906] cd
on cd.CSTMR_NUM = cast(eh.[CIS_NUMBER ] as numeric(20,0))
Where (IsNumeric(eh.[CIS_NUMBER ])=1)

Related

How do i extract xml data stored as data in a table column with a complex formed sql

I have XML data that comes in from a third party (so I cannot change the XML format) and gets stored in a table.
An example XML message format
<MedicalAidMessage xmlns="test.co.za/messaging" version="6.0">
<BenefitCheckResponseMessage>
<FinancialResponseDetails>
<FinancialResponseLines>
<FinancialResponseLine>
<LineIdentifier>1</LineIdentifier>
<RequestedAmount>1000</RequestedAmount>
<AmountToProvider>800</AmountToProvider>
<AmountToMember>0</AmountToMember>
<MemberLiableAmount>200</MemberLiableAmount>
<MemberNotLiableAmount>0</MemberNotLiableAmount>
<TariffCode>12345</TariffCode>
<LineResponseCodes>
<LineResponseCode>
<Sequence>1</Sequence>
<Code>274</Code>
<Description>We have not paid the amount claimed because the funds in the Medical Savings are used up.</Description>
<Type>Info</Type>
</LineResponseCode>
<LineResponseCode>
<Sequence>2</Sequence>
<Code>1239</Code>
<Description>We have applied a co-payment on this claim, in line with the member’s plan benefit for MRI and CT scans.</Description>
<Type>Info</Type>
</LineResponseCode>
</LineResponseCodes>
</FinancialResponseLine>
</FinancialResponseLines>
</FinancialResponseDetails>
</BenefitCheckResponseMessage>
</MedicalAidMessage>
I have tried the following code to get the Tariffcode, RequestedAmount, AmountToProvider and AmountToMember
DECLARE #XMLData XML = (select top 1 replace(br.xmlmessage,'<?xml version="1.0" encoding="UTF-8"?>','')
from benefitcheckresponse br
inner join benefitcheck bc on bc.id = br.BenefitCheckId
where bc.id =1562
order by bc.id desc)
SELECT
[TariffCode] = Node.Data.value('TariffCode', 'vacrhar(50)'),
[RequestedAmount] = Node.Data.value('RequestedAmount', 'float)'),
[AmountToProvider] = Node.Data.value('AmountToProvider', 'float)'),
[AmountToMember] = Node.Data.value('AmountToMember', 'float)')
FROM #XMLData.nodes('/*/FinancialResponseLine/') Node(Data)
The problem I am getting is that it is giving me the following error message
Msg 9341, Level 16, State 1, Line 12 XQuery [nodes()]: Syntax error
near '', expected a step expression.
How do I resolve that error?
How would I include the results for multiple lines when there multiple line responses?
How would I include the values from the sub nodes to the line response nodes?
You would be better off with syntax like this, if I am honest. I wasn't able to complete the ORDER BY clause for you, as I don't know what column to order by, but as you have a TOP (1) you need one. You also need to define your XML namespace, which you have not, which would have resulted in no rows being returned:
WITH XMLNAMESPACES(DEFAULT 'test.co.za/messaging')
SELECT TOP (1)
FRL.FRL.value('(TariffCode/text())[1]','int') AS TariffCode,
FRL.FRL.value('(RequestedAmount/text())[1]','int') AS RequestedAmount, --I doubt float is the correct data type here
FRL.FRL.value('(AmountToProvider/text())[1]','int') AS AmountToProvider, --I doubt float is the correct data type here
FRL.FRL.value('(AmountToMember/text())[1]','int') AS AmountToMember --I doubt float is the correct data type here
FROM dbo.benefitcheckresponse br
INNER JOIN benefitcheck bc ON bc.id = br.BenefitCheckId
CROSS APPLY br.xmlmessage.nodes('MedicalAidMessage/BenefitCheckResponseMessage/FinancialResponseDetails/FinancialResponseLines/FinancialResponseLine') FRL(FRL)
WHERE bc.id = 1562
ORDER BY {Column Name(s)};

Snowflake copy into not recognising timestamp

Any suggestions on the below, i am trying to use copy into to move parquet files from S3 into snowflake table. Col1 is a timestamp and the rest are strings.
copy into table1 from
(select $1:col1, $1:col2, $1:col3
from #stage/path)
file_format = (format_name = parquet_format);
and getting the following error
Failed to cast variant value "20050111 00:00:00" to TIMESTAMP_NTZ
I have tried
copy into table1 from
(select to_timestamp($1:col1, 'yyyymmdd hh:mi:ss'), $1:col2, $1:col3
from #stage/path)
file_format = (format_name = parquet_format);
but getting the error
Error: too many arguments for function [TO_TIMESTAMP(GET(STAGE.$1, 'col1'), 'yyyymmdd hh:mi:ss')] expected 1, got 2 (line 130)
Any ideas
What's happening is this in this expression:
(select to_timestamp($1:col1, 'yyyymmdd hh:mi:ss')
This part: $1:col1 is resolving to an object rather than a primitive data type. This is what's leading to the error message about getting 2 arguments instead of one.
Changing this part of the expression to $1:col1::string casts the expression as a primitive type - string or varchar. This is the type of parameter the to_timestamp function is expecting. The final statement should be:
copy into table1 from
(select to_timestamp($1:col1::string, 'yyyymmdd hh:mi:ss'), $1:col2, $1:col3
from #stage/path)
file_format = (format_name = parquet_format);

Conversion failed when converting the varchar value to data type int in sql query

I'm trying a dynamic SQL query but I'm getting an error about conversion but can't figure out what the problem is.
Here's my query :
DECLARE #VarSubCriBusqueda VARCHAR(MAX)
SET #VarSubCriBusqueda = 'Marca'
DECLARE #InputString VARCHAR(MAX)
SET #InputString = '%'
SELECT
Marcas.MarcaID, Marcas.Marca, Clases.ClaseNo, Marcas.Codigo, Propietarios.Propietario
FROM
Marcas
LEFT OUTER JOIN
Propietarios ON marcas.PropietarioID = Propietarios.PropietarioID
LEFT OUTER JOIN
Clases ON Marcas.ClaseIntID = clases.ClaseID
LEFT OUTER JOIN
Clientes ON Clientes.ClienteID = Marcas.ClienteID
WHERE
CASE #VarSubCriBusqueda
WHEN 'Clases.ClaseNo'
THEN Clases.ClaseNo
WHEN 'Codigo'
THEN Codigo
WHEN 'Propietarios.Propietario'
THEN Propietarios.Propietario
WHEN 'Clientes.Empresa'
THEN Clientes.Empresa
WHEN 'Contacto'
THEN Marcas.Contacto
WHEN 'Marca'
THEN Marca
END LIKE #InputString
It end with the following message:
Msg 245, Level 16, State 1, Line 6
Conversion failed when converting the varchar value 'ACADEMY AWARDS' to data type int.
Any help?
In all likelihood. you are missing the fact that a case expression returns a single type. And, if any of the then or else clauses are numbers, then all are converted to numbers. I imagine that one or more of the columns are numbers. One fix is explicit conversion.
A better fix is to get rid of the case expression entirely:
WHERE (#VarSubCriBusqueda = 'Clases.ClaseNo' AND Clases.ClaseNo like #InputString) OR
(#VarSubCriBusqueda = 'Codigo' AND Codigo like #InputString) OR
. . .
And even with this formulation, you should use the correct comparison for your type. So, if you have a number, LIKE doesn't seem appropriate.

error converting datatype conversion on single vendoritemnumber in duplicate rows

Sql server query shows error :
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
Here is the query:
WITH employee AS (
SELECT distinct vendoritemnumber,VendorItemId,
VendorItemDescription,
VendorItemDescriptionAlias,VendorId,BrgItemId,itemconversionFactor,
orderbyuomid,pricebyuomid,vendorcasedescription,manufacturernumber,skunumber,[weight],
averageweight,currentprice,taxable,[status],createddate,inactivedate,lastpurchaseddate,
lastupdatedby,lastupdateddate,vendorpercent,vendorfreight,brandid,pack,size,inventorycategoryid,
binlocation,inventorylocation,inventorystatus,physicalinventoryconversionfactor,stateswhereused,
conceptwhereused,priceupdatedate,size_uom,pack_uom,isdeleted,'' as id,'' itemid,'' as oldprice,
'' as newprice,'' as dateupdated,'' as weekenddate,'' as lastpurdate
FROM VendorItems WHERE BrgItemId=6056)
SELECT * FROM employee
UNION ALL
SELECT '' as ven,v.VendorItemId,
v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
from [dbo].[VendorItems] v join PriceHistory ph
on ph.ItemId=v.VendorItemId join brgitems brg on
brg.brgitemid=v.BrgItemId
WHERE v.BrgItemId=6056
group by vendoritemnumber,v.VendorItemId,v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
I want to show single vendoritemnumber in duplicate rows..Any suggestion??
Where is the error??
SQL Server cannot convert an empty string to NUMERIC data type. For example, the following will yield the same error:
SELECT CONVERT(NUMERIC, '')
Replace empty strings ('') with 0 or NULL.
#manoj .Just FYI to know exact error point , double click on the error in message window .It shows the exact line of code on error, Also try to check if any empty values are there for that column and as mentioned by #Serge SQL throws error while any data type is converted to numeric and if its value is empty. Best solution is to add WHERE clause and filter those cases.

Error using to_char // to_timestamp

I have a database in PostgreSQL and I'm developing an application in PHP using this database.
The problem is that when I execute the following query I get a nice result in phpPgAdmin but in my PHP application I get an error.
The query:
SELECT t.t_name, t.t_firstname
FROM teachers AS t
WHERE t.id_teacher IN (
SELECT id_teacher FROM teacher_course AS tcourse
JOIN course_timetable AS coursetime
ON tcourse.course = coursetime.course
AND to_char(to_timestamp('2010-4-12', 'YYYY-MM-DD'),'FMD') = (coursetime.day +1)
)
AND t.id_teacher NOT IN (
SELECT id_teacher FROM teachers_fill WHERE date = '2010-4-12'
)
ORDER BY t.t_name ASC
And this is the error in PHP
operator does not exist: text = integer (to_timestamp('', 'YYYY-MM-DD'),'FMD') =
(courset... ^ HINT: No operator matches the given name and argument type(s).
You might need to add explicit type casts.
The purpose to solve this error is to use the ORIGINAL query in php with :
$date = "2010"."-".$selected_month."-".$selected_day;
SELECT ...
AND to_char(to_timestamp('$date', 'YYYY-MM-DD'),'FMD') = (coursetime.day +1)
)
AND t.id_teacher NOT IN (
SELECT id_teacher FROM teachers_fill WHERE date = '$date'
)
The error message seems quite clear to me. You are mixing strings and numbers. More precisely, you are converting a string ('2010-4-12') to a timestamp, then to a string, then comparing to an int. This is a type mess, and postgresql is quite strict with typing (for good reasons). What are you trying to do here ?
to_char(to_timestamp('2010-4-12', 'YYYY-MM-DD'),'FMD') = (coursetime.day +1))
Further, you should use a TIMESTAMP, just a DATE.
If (I'm not sure) you are tring to compare the day of week from a date formated as 'YYYY-MM-DD' to a given value (as an integer), you should better use date_part. For example (not tested):
date_part('dow' , to_date('2010-4-12', 'YYYY-MM-DD') ) = coursetime.day + 1

Resources