0

I have trying to update/create a table from the XML string using the below stored procedure.

CREATE PROCEDURE [dbo].[usp_Import_Material_Charge]  
(@passedXMLStringForSQL xml)  
AS  
BEGIN

SET NOCOUNT ON

            
            DECLARE @xmlHandle INT;

            EXEC sp_xml_preparedocument @xmlHandle output, @passedXMLStringForSQL

            SELECT * into ClothingMaterialRecon..Material_Charge
            FROM OPENXML (@xmlHandle, '/NewDataSet/Sheet2', 3)
            WITH ([Material]            varchar(50)       'Material',  
                  [Description]         varchar(50)       'Description',  
                  [MRP]             decimal(7, 2)     'MRP',  
                  [Material_Charge]     decimal(7, 2)     'New_Material_Charge')
            
            EXEC sp_xml_removedocument @xmlHandle

END

I have been successful in creating the table so far. But I was thinking of trying something new.

I was trying to replace '/NewDataSet/Sheet2' rowpattern(XPath) with a scalar variable.

The variable will contain the XPath. I wanted to extract the XPath by querying in the XML itself, but no luck so far.

Is there a way to get the XPath by querying the XML string so that we could use it for any kind of XML? XML can be different types and not every XML will have a same pattern of XPath as shown above.

Is there a way to make this dynamic/non-dependent on manually searching the XML for XPath?

2
  • 1
    Where would Material end up? You can have XPaths like //Sheet2, which will search for the Sheet2 element anywhere in the document. Querying the document itself just to construct a path is not meaningful: if you can find out the path dynamically, you can also query it dynamically without determining it first. Note that sp_xml_preparedocument is the old (pre-SQL Server 2005) way of accessing XML; the XML methods are generally more convenient as they do not require futzing about with XML handles. Commented Jun 9, 2021 at 8:28
  • If namespaces are involved, see this: stackoverflow.com/a/22818721/3710053 Commented Jun 9, 2021 at 9:05

0

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.