Reputation: 13976
I am not very familiar with using XML in SQL Server and I have been asked to update this stored procedure and modify it to apply some math to a field before inserting it into the table.
Here is some example code:
CREATE PROCEDURE [spNewUser]
@UserInfo xml
AS
BEGIN
IF @UserInfo.exist('/UserInfo') = 1
BEGIN
DECLARE
@FirstName varchar(40),
@LastName varchar(40),
@Height varchar(10)
SELECT
@FirstName = Personal.query('FirstName').value('.','varchar(25)'),
@LastName = Personal.query('LastName').value('.','varchar(50)'),
@Height = NULLIF(Personal.query('HeightFt').value('.','varchar(3)') + '.' + Personal.query('HeightIn').value('.','varchar(3)'),'.')
FROM
@UserInfo.nodes('/UserInfo/Personal') AppInfo(Personal)
END
BEGIN
Now I understand (in general) everything happening. We used to store height (in feet and inches) as 'FootValue'.'InchValue'
because we didn't use it for anything, but now we want to use it for something. We are going to store it as an int now, and save the number of inches. I want to do HeightFt * 12 + HeightIn
but I am unsure the safest way to convert and do the math. I am not sure how to do the query('HeightFt').value(???)
statement. I would want it to return 0 if not existent.
Upvotes: 1
Views: 292
Reputation: 755371
I would recommend to store numeric values as numerics - not varchar(10)
. Basically, you should extract those values from the XML and then do your calculation afterwards:
DECLARE
@FirstName varchar(40),
@LastName varchar(40),
@HeightFt decimal(16, 4),
@HeightIn decimal(16, 4)
SELECT
@FirstName = Personal.value('(FirstName)[1]', 'varchar(25)'),
@LastName = Personal.value('(LastName)[1]', 'varchar(50)'),
@HeightFt = ISNULL(Personal.value('(HeightFt)[1]', 'DECIMAL(6, 1)'), 0.0),
@HeightIn = ISNULL(Personal.value('(HeightIn)[1]', 'DECIMAL(6, 1)'), 0.0)
FROM
@UserInfo.nodes('/UserInfo/Personal') AppInfo(Personal)
DECLARE @Calculated DECIMAL(8, 2)
SET @Calculated = @HeightFt * 12 + @HeightIn
Upvotes: 2