Hello,
I am accepting an input parameter of xml type so that i can accept a list of insurance plans on a transaction. I need to take the xml parameter and shred it into a tale variable so that i can process some logic. How can i shred the XML into my table variable.
Here's a script to create a sample table with data in it;
/*
CREATE TABLE PlanData(PlanPos INT IDENTITY, PayerDX INT, PlanDX INT, PayPct DECIMAL(6,2))
INSERT PlanData(PayerDX, PlanDX, PayPct)
VALUES(10, 20, 80)
INSERT PlanData(PayerDX, PlanDX, PayPct)
VALUES(25, 50, 10)
drop table PlanData
*/
DECLARE @xmlPlans XML
SET @xmlPlans = (SELECT PlanPos, PayerDX, PlanDX, PayPct
FROM PlanData
ORDER BY PlanPos
FOR XML RAW('plan'), ROOT('plans')
)
print CAST(@xmlPlans AS NVARCHAR(max))
/* We must convert the XML passed in containing all of the insurance payer plan
data into a usable format for the current scoping. */
DECLARE @tblPlans TABLE(PlanPos INT, IPDX INT, IPPDX INT, PayPct decimal(6, 2))
-- /* Note that the table is built in order from Primary through the last plan */
-- INSERT @tblPlans (PlanPos, IPDX, IPPDX, PayPct)
-- SELECT x.item.value('@PlanPos[1]', 'INT') AS PlanPos,
-- x.item.VALUE('@IPDX[1]', 'INT') AS IPDX,
-- x.item.VALUE('@IPPDX[1]', 'INT') AS IPPDX,
-- x.item.VALUE('@PayPct[1]', 'decimal(6, 2)') AS PayPct
-- FROM @xmlPlans.nodes('//items/item') AS x(item)
INSERT @tblPlans (PlanPos, IPDX, IPPDX, PayPct)
SELECT T.plann.value('@PlanPos', 'int') AS PlanPos
,T.plann.VALUE('@PayerDX', 'INT') AS IPDX
,T.plann.VALUE('@PlanDX', 'INT') AS IPPDX
,T.plann.VALUE('@PayPct', 'decimal(6, 2)') AS PayPct
FROM @xmlPlans.nodes('plans/plan') as T(plann)
---- Attribute-centered XML
--DECLARE @data XML
--SET @data = '<data><customer id="1" name="Allied Industries"/><customer id="2" name="Trades International"/></data>';
--
--DECLARE @tblCust TABLE(id INT, [name] VARCHAR(20))
--
--
---- Using the value() method
--INSERT @tblCust (id, [name])
--SELECT T.customer.value('@id', 'INT') AS customer_id,
-- T.customer.value('@name', 'VARCHAR(20)') AS customer_name
--FROM @data.nodes('data/customer') AS T(customer);
--
--SELECT id AS dx, name AS CustName FROM @tblCust
-- SELECT x.item.value('@PlanPos[1]', 'INT') AS PlanPos,
-- x.item.VALUE('@IPDX[1]', 'INT') AS IPDX,
-- x.item.VALUE('@IPPDX[1]', 'INT') AS IPPDX,
-- x.item.VALUE('@PayPct[1]', 'decimal(6, 2)') AS PayPct
-- FROM @xmlPlans.nodes('//items/item') AS x
SELECT
p.PlanPos AS PlanPos,
p.IPDX AS IPDX,
p.IPPDX AS IPPDX,
p.PayPct AS PayPct
FROM @tblPlans p
You will also see me attempts at it that are failing.
Thank you,
Brian