1

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

What will this return if HeightFt or HeightIn doesn't exist?
@Remus: ok, sure - not fitting here; that's just my "usual" default (for invoices and stuff like that) ... adapt as needed and as you see fit :-)
@marc Why did you reply to his and not mine :p I just want to know what the default value is!
@marc sorry if I didn't show it very well, I meant a bit of humour (and wasn't upset!) in that last comment. Thanks for your help, this worked out great!

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.