2

I am new to this and I am trying to learn more about SQL. I have this example and still not able to figure it out why I am getting this error:

DECLARE @xmlprice XML = '<price>1234567</price>'
DECLARE @price DECIMAL(19,4);

SET @price = @xmlprice.value('sum(price)', 'DECIMAL(19,4)');

I get the following error:

Error converting data type nvarchar to numeric.

6
  • 1
    Can you share with us what you found when you Google'd that error message and attempted to troubleshoot it? Commented Aug 22, 2018 at 21:14
  • 2
    Yes i did, but the funny thing is that when i reduce it to 6 digits it works when i try using 7 digits it failed. I did research on google but nothing relate it to this specific problem. The precision it suppose to work with 19 digits. Commented Aug 22, 2018 at 21:15
  • Possible duplicate of SQL Server: Error converting data type nvarchar to numeric Commented Aug 22, 2018 at 21:16
  • I'm not an xml guy, but decimal(19,4) has a scale of 15 (digits to the left of the decimal). select len('price123456price') = 16. Commented Aug 22, 2018 at 21:23
  • Hi @Jayvi03 , Please convert @xmlprice.value('sum(price)') to decimal using SQL Cast or Convert function Commented Aug 22, 2018 at 21:23

2 Answers 2

1

I think that's a bug, but it's such a strange thing to do I'm not sure. Normally you would project the XML values out first, and then aggregate them.

eg

select @xmlprice.value('(/price)[1]','decimal(19,4)');

This expression says to start at the root '/' and then find all the 'price' elements, pick the first one, and extract its value.

You may want to post this on the SQL Server feedback site for the product team to evaluate.

Sign up to request clarification or add additional context in comments.

Comments

1

Based on your recommendation, I cast my price value to decimal with a FLWOR Statement and Iteration (XQuery) before the sum.

DECLARE @xmlprice XML = '<price>1234567</price>'
DECLARE @price DECIMAL(19,4);

SET @price = @xmlprice.value('sum(for $price in //price return $price cast as xs:decimal?)', 'DECIMAL(19,4)');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.