SQL Server XML Date Import - sql

Having trouble importing an xml date feild into sql server, the other feilds are fine. I have tried numerous way's but it always returns as null. Any help please
2014-02-18T12:15:21.357 is the issue
The XML is
<?xml version="1.0" encoding="utf-8"?>
<MISRoot xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS">
<Claims>
<Claim>
<Amalgamation>
<ChannelSolutions />
<Name i:nil="true" />
</Amalgamation>
<Appointments>
<Appointment>
<Access />
<AccessGranted>true</AccessGranted>
<AppointmentId>320</AppointmentId>
<EnterTime>2014-02-18T12:15:21.357</EnterTime>
<LeaveTime i:nil="true" />
<Name i:nil="true" />
</Appointment>
</Appointments>
<CustomProducts />
<Id>1220</Id>
<Payments />
<Tasks />
</Claim>
</Claims>
</MISRoot>
THE SQL is
CREATE TABLE [dbo].[xmlImportAppointments](
[ClaimId] [int] not null,
[AppointmentAUTO] [int] not NULL,
[AppointmentId] [int] not NULL,
[EnterTime] [datetime] NULL,
[LeaveTime] [datetime] NULL,
[AccessGranted] [nchar](20) NULL,
) ON [PRIMARY]
GO
WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS')
INSERT INTO xmlImportAppointments
(ClaimId, AppointmentAUTO, AppointmentId, EnterTime, LeaveTime, AccessGranted)
SELECT
ClaimId = xmldata.value('(Claim/Id)[1]', 'int'),
AppointmentAUTO = xmldata.value('(Claim/Appointments/Appointment/AppointmentId)[1]', 'int'),
AppointmentId = xmldata.value('(Claim/Appointments/Appointment/AppointmentId)[1]', 'int'),
EnterTime = xmldata.value('(Claims/Appointment/Appointments/EnterTime)[1]', 'datetime'),
LeaveTime = xmldata.value('(Claims/Appointment/Appointments/EnterTime)[1]', 'datetime'),
AccessGranted = xmldata.value('(Claim/Appointments/Appointment/AccessGranted)[1]', 'NCHAR(20)')
FROM
(SELECT CAST(x AS XML)
FROM OPENROWSET(BULK '\\XMLTest\increment.xml',
SINGLE_BLOB) AS T(x)) AS T(x)
CROSS APPLY
x.nodes('/MISRoot/Claims') AS X(xmldata);
SELECT * FROM xmlImportAppointments

You had a problem with your XQuery I had copied your File into a XML variable and was able to retrieve using the following query.
DECLARE #MyXMLVariable XML =
'<?xml version="1.0" encoding="utf-8"?>
<MISRoot xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS">
<Claims>
<Claim>
<Amalgamation>
<ChannelSolutions />
<Name i:nil="true" />
</Amalgamation>
<Appointments>
<Appointment>
<Access />
<AccessGranted>true</AccessGranted>
<AppointmentId>320</AppointmentId>
<EnterTime>2014-02-18T12:15:21.357</EnterTime>
<LeaveTime i:nil="true" />
<Name i:nil="true" />
</Appointment>
</Appointments>
<CustomProducts />
<Id>1220</Id>
<Payments />
<Tasks />
</Claim>
</Claims>
</MISRoot>';
WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/IGUK.Evolution.FieldToolLite.Lib.MIS')
SELECT #MyXMLVariable.value('(MISRoot/Claims/Claim/Appointments/Appointment/EnterTime)[1]','DATETIME')
You did not specify the full correct path to EnterTime
'(MISRoot/Claims/Claim/Appointments/Appointment/EnterTime)[1]' --Correct
'(Claims/Appointment/Appointments/EnterTime)[1]' --Yours
Appointment is child of Appointments not the other way around and Claim is a child of Claims best way to do this is to look at Open tags and closed tags

Related

Extracting data from XML Array using SQL

I have the following XML and would like to extract the PrimaryTeams, SecondaryTeams and OverflowTeams arrays from this and either have them comma separated or one per row.
I have the following xml:
declare #xml xml
set #xml = '<SimpleStrategy xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD">
<Id>00000000-0000-0000-0000-000000000000</Id>
<Name>Default</Name>
<AcceptedCLIs xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>07811353995</d2p1:string>
</AcceptedCLIs>
<ActiveHours>
<FridayEnd />
<FridayStart />
<MondayEnd />
<MondayStart />
<SaturdayEnd />
<SaturdayStart />
<SundayEnd />
<SundayStart />
<ThursdayEnd />
<ThursdayStart />
<TuesdayEnd />
<TuesdayStart />
<UseIndividualWeekDays>false</UseIndividualWeekDays>
<WednesdayEnd />
<WednesdayStart />
<WeekdayEnd />
<WeekdayStart />
</ActiveHours>
<AgentUserName />
<AllowRouteDuringFinalMessage>false</AllowRouteDuringFinalMessage>
<CRMPrefix />
<DirectDDIMessage />
<DirectDDIPassThrough>false</DirectDDIPassThrough>
<EmergencyBusyBack>false</EmergencyBusyBack>
<EmergencyDivertNumber />
<EmergencyWavFile />
<FinallyDivertNumber />
<FinallyDrop>true</FinallyDrop>
<FinallyMessageFile />
<MaximumQueueLength>0</MaximumQueueLength>
<MaximumQueueWait>0</MaximumQueueWait>
<MinimumRingTime>4000</MinimumRingTime>
<MusicOnHold />
<MusicWhileWaiting />
<NumberOfRings>2</NumberOfRings>
<OutOfHoursDivertNumber />
<OutOfHoursDrop>true</OutOfHoursDrop>
<OutOfHoursMessage />
<OverflowMessage />
<OverflowTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
<PrimaryTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:int>3</d2p1:int>
<d2p1:int>1</d2p1:int>
</PrimaryTeams>
<Priority>1</Priority>
<RecordAgent>false</RecordAgent>
<RecordCall>true</RecordCall>
<RecordCustomer>false</RecordCustomer>
<RegulatoryMessage>Default.wav</RegulatoryMessage>
<SecondaryOverflowMessage />
<SecondaryTeams xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
<SendBusyIfQueueTooLong>false</SendBusyIfQueueTooLong>
<SendBusyIfWaitTooLong>false</SendBusyIfWaitTooLong>
<TimeInOverflow>-1</TimeInOverflow>
<TimeWithDirectDDI>20000</TimeWithDirectDDI>
<TimeWithPrimaryTeams>-1</TimeWithPrimaryTeams>
<TimeWithSecondaryTeams>20000</TimeWithSecondaryTeams>
<UseDirectDDI>false</UseDirectDDI>
<UsePAM>false</UsePAM>
<UseSecondaryTeams>false</UseSecondaryTeams>
<WrapTime>40000</WrapTime>
</SimpleStrategy>'
I then created the following SQL Statement to try and extract the Teams
;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' as i, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays' as d2p1,
DEFAULT 'http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD')
SELECT #xml,
#xml.value('(/SimpleStrategy/Name)[1]', 'varchar(255)'),
#xml.value('(/SimpleStrategy/PrimaryTeams)[1]', 'int') as PrimaryTeams,
#xml.value('(/SimpleStrategy/SecondaryTeams)[1]', 'int') as SecondaryTeams,
#xml.value('(/SimpleStrategy/OverflowTeams)[1]', 'int') as OverflowTeams
But all I get is the TeamID's concatenated together.
,PrimaryTeams,SecondaryTeams,OverflowTeams
Default,31,0,0
Any ideas?
Thanks
Matt
Your XML shows two team IDs in <PrimaryTeams>, while both other team nodes are empty... You did not tell us anything about the expected counts in there. However, the following approach will return a kind of entity-value-pairs with all IDs for all Teams. Hope this is what you need:
;WITH XMLNAMESPACES ('http://www.w3.org/2001/XMLSchema-instance' as i, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays' as d2p1,
DEFAULT 'http://schemas.datacontract.org/2004/07/Synthesys.Switch.ACD')
SELECT 'Name' AS Caption
,1 AS RowInx
,#xml.value('(/SimpleStrategy/Name)[1]', 'varchar(255)') AS Content
UNION ALL
SELECT 'Primary Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/PrimaryTeams/d2p1:int') A(t)
UNION ALL
SELECT 'Secondary Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/SecondaryTeams/d2p1:int') A(t)
UNION ALL
SELECT 'Overflow-Team'
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
,t.value('.','varchar(255)')
FROM #xml.nodes('/SimpleStrategy/OverflowTeams/d2p1:int') A(t);

FORXML SQL Group By Element

I am trying to group some elements together under one node. This is my current SQL;
declare #xml xml
set #xml = (
select (
select
'DERIVED' '#type',
m.NuixDerivedFieldName '#name', (
SELECT
NuixFieldType as 'metadata/#type',
NuixFieldName as 'metadata/#name'
from eddsdbo.MetadataMapping m1
where m1.NuixDerivedFieldName = m.NuixDerivedFieldName
for xml path ('first-non-blank'), type
)
from (select distinct NuixDerivedFieldName from eddsdbo.MetadataMapping) m
for xml path ('metadata'))
)
;WITH XMLNAMESPACES(DEFAULT 'http://nuix.com/fbi/metadata-profile')
select #xml for XML PATH ('metadata-list'), ROOT ('metadata-profile')
Which gives me the following output;
<metadata-profile xmlns="http://nuix.com/fbi/metadata-profile">
<metadata-list>
<metadata type="DERIVED" name="Barcode" xmlns="">
<first-non-blank>
<metadata type="CUSTOM" name="Barcode" />
</first-non-blank>
<first-non-blank>
<metadata type="EVIDENCE" name="Barcode" />
</first-non-blank>
</metadata>
I want to group together elements together which have the same 'name' attribute of the metadata element under the <first-non-blank> element.
The desired output should be;
<metadata-profile xmlns="http://nuix.com/fbi/metadata-profile">
<metadata-list>
<metadata type="DERIVED" name="Barcode" xmlns="">
<first-non-blank>
<metadata type="CUSTOM" name="Barcode" />
<metadata type="EVIDENCE" name="Barcode" />
</first-non-blank>
</metadata>
...
My database looks something like this;
NuixFieldName NuixFieldType NuixDerivedFieldName
------------------------------ ------------------------------ ------------------------------
_EmailEntryID PROPERTY EmailEntryID
Audited Audited Audited
Author PROPERTY Author
Barcode CUSTOM Barcode
Barcode EVIDENCE Barcode
I would also like to remove the xlmns namespace identifier from the metadata elements.
Thanks in advance!
You could try this
DECLARE #SampleData AS TABLE
(
NuixFieldName varchar(20),
NuixFieldType varchar(20),
NuixDerivedFieldName varchar(20)
)
INSERT INTO #SampleData
VALUES
('_EmailEntryID','PROPERTY','EmailEntryID'),
('Audited', 'Audited ','Audited'),
('Author ', 'PROPERTY','Author '),
('Barcode', 'CUSTOM ','Barcode'),
('Barcode', 'EVIDENCE','Barcode')
DECLARE #xml XML
SET #xml = (
SELECT
-- sd.NuixDerivedFieldName AS [#name],
'DERIVED' AS [#type],
sd.NuixDerivedFieldName AS [#name],
(
SELECT
sd2.NuixFieldType as '#type',
sd2.NuixFieldName as '#name'
FROM #SampleData sd2 WHERE sd2.NuixDerivedFieldName = sd.NuixDerivedFieldName
FOR XML PATH ('metadata'),ROOT('first-non-blank'), TYPE
)
FROM (select DISTINCT sd.NuixDerivedFieldName from #SampleData sd ) sd
FOR XML PATH('metadata'), ROOT('metadata-list'),TYPE
)
;WITH XMLNAMESPACES(DEFAULT 'http://nuix.com/fbi/metadata-profile')
SELECT #xml FOR XML PATH (''),ROOT('metadata-profile')
return:
<metadata-profile xmlns="http://nuix.com/fbi/metadata-profile">
<metadata-list>
<metadata type="DERIVED" name="Audited">
<first-non-blank>
<metadata type="Audited " name="Audited" />
</first-non-blank>
</metadata>
<metadata type="DERIVED" name="Author ">
<first-non-blank>
<metadata type="PROPERTY" name="Author " />
</first-non-blank>
</metadata>
<metadata type="DERIVED" name="Barcode">
<first-non-blank>
<metadata type="CUSTOM " name="Barcode" />
<metadata type="EVIDENCE" name="Barcode" />
</first-non-blank>
</metadata>
<metadata type="DERIVED" name="EmailEntryID">
<first-non-blank>
<metadata type="PROPERTY" name="_EmailEntryID" />
</first-non-blank>
</metadata>
</metadata-list>
</metadata-profile>

Extract proper data from a sql server XML column using XQuery

I am having an issue trying to get proper data from an XML type column:
"<"ArrayOfAccountInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.Balance.com/">
"<"AccountInformation>
"<"AccountNumber xmlns="https://Safouenmzah.com/">0100000000"<"/AccountNumber>
"<"OutstandingAmount xmlns="https://Safouenmzah.com/">-909.55"<"/OutstandingAmount>
"<"LastBilledAmount xmlns="https://Safouenmzah.com/" />
"<"LastPaidDate xmlns="https://Safouenmzah.com/" />
"<"Severance xmlns="https://Safouenmzah.com/" />
"<"PaymentAmount xmlns="https://Safouenmzah.com/" />
"<"DistributedAmount xmlns="https://Safouenmzah.com/">$"<"/DistributedAmount>
"<"AccountInfo xmlns="https://Safouenmzah.com/">Safouen Mzah - Residential"<"/AccountInfo>
"<"/AccountInformation>
"<"/ArrayOfAccountInformation>
I am using this sql code:
;WITH XMLNAMESPACES ('http://www.Balance.com/' AS ns)
SELECT xmlResult.value('(/ns:ArrayOfAccountInformation)[1]','varchar(8000)') AS AcctInfo
FROM [dbo].[BalanceEnquiry_Transactions_Tracker]
WHERE BanlanceEnquiry_Transc_ID = 4
GO
This the result I am receiving always:
0100000000-909.55AEDSafouen Mzah - Residential
This is the expected result:
0100000000
Can some one help on this please?
Finally I figured it out.
declare #XML XML;
set #XML = '
"<"ArrayOfAccountInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.Balance.com/">
"<"AccountInformation>
"<"AccountNumber xmlns="https://Safouenmzah.com/">0100000000"<"/AccountNumber>
"<"OutstandingAmount xmlns="https://Safouenmzah.com/">-909.55"<"/OutstandingAmount>
"<"LastBilledAmount xmlns="https://Safouenmzah.com/" />
"<"LastPaidDate xmlns="https://Safouenmzah.com/" />
"<"Severance xmlns="https://Safouenmzah.com/" />
"<"PaymentAmount xmlns="https://Safouenmzah.com/" />
"<"DistributedAmount xmlns="https://Safouenmzah.com/">$"<"/DistributedAmount>
"<"AccountInfo xmlns="https://Safouenmzah.com/">Safouen Mzah - Residential" <"/AccountInfo>
"<"/AccountInformation>
"<"AccountInformation>
"<"AccountNumber xmlns="https://Safouenmzah.com/">0200000000"<"/AccountNumber>
"<"OutstandingAmount xmlns="https://Safouenmzah.com/">-908.55"<"/OutstandingAmount>
"<"LastBilledAmount xmlns="https://Safouenmzah.com/" />
"<"LastPaidDate xmlns="https://Safouenmzah.com/" />
"<"Severance xmlns="https://Safouenmzah.com/" />
"<"PaymentAmount xmlns="https://Safouenmzah.com/" />
"<"DistributedAmount xmlns="https://Safouenmzah.com/">$"<"/DistributedAmount>
"<"AccountInfo xmlns="https://Safouenmzah.com/">Safouen Mzah - Expat"<"/AccountInfo>
"<"/AccountInformation>
"<"/ArrayOfAccountInformation>
'
;WITH XMLNAMESPACES ('http://www.Balance.com/' AS ns)
-- To get the outstanding amount of the first Account from the returned array
SELECT #XML.value('(/*[1]/*[1]/*[2])', 'varchar(200)') As OutstandingAmount1
-- To get the outstanding amount of the second Account from the returned array
SELECT #XML.value('(/*[1]/*[2]/*[2])', 'varchar(200)') As OutstandingAmount2
OutstandingAmount1
-909.55
OutstandingAmount2
-908.55
You can use nodes() to shred the XML and get the values in one resultset.
with xmlnamespaces('https://Safouenmzah.com/' as ns,
default 'http://www.Balance.com/')
select T.X.value('(ns:OutstandingAmount/text())[1]', 'varchar(200)')
from #XML.nodes('/ArrayOfAccountInformation/AccountInformation') as T(X)
SQL Fiddle

SQL xml query returns null

I have the following XML:
<Matter>
<CriticalDates>
<CriticalDate>
<CriticalDateId>2</CriticalDateId>
<Name>Instruction Date</Name>
<Value_FieldId>9F21</Value_FieldId>
<Confirmed_FieldId />
<Status>In Progress</Status>
<ConfirmStatus />
<CompPercent>0</CompPercent>
<Order>0</Order>
<Value>2014-03-28T06:00:00+11:00</Value>
<Confirmed>false</Confirmed>
</CriticalDate>
<CriticalDate>
<CriticalDateId>-2</CriticalDateId>
<Name>Completion Date</Name>
<Value_FieldId>9F22</Value_FieldId>
<Confirmed_FieldId>9F27</Confirmed_FieldId>
<Status>Complete</Status>
<ConfirmStatus />
<CompPercent>0</CompPercent>
<Order>1</Order>
<Value />
<Confirmed>false</Confirmed>
</CriticalDate>
<CriticalDate>
<CriticalDateId>-3</CriticalDateId>
<Name>Not Proceeding Date</Name>
<Value_FieldId>9F23</Value_FieldId>
<Confirmed_FieldId />
<Status>Not Proceeding</Status>
<ConfirmStatus />
<CompPercent>0</CompPercent>
<Order>2</Order>
<Value />
<Confirmed>false</Confirmed>
</CriticalDate>
</CriticalDates>
</Matter>
To select all the nodes as rows i'm using:
SELECT
MatterId,
MatterXml,
MD.CD.value('(Name)[1]', 'VARCHAR(50)') AS 'Name',
MD.CD.value('(Status)[1]', 'VARCHAR(50)') AS 'Status',
MD.CD.value('(value)[1]', 'DATE') AS 'CriticalDate',
MD.CD.value('(Confirmed)[1]', 'VARCHAR(50)') AS 'Confirmed'
FROM
dbo.Matter m
CROSS APPLY m.MatterXml.nodes('/Matter/CriticalDates/CriticalDate') AS MD(CD)
When i run this i get 3 rows back but all CriticalDates return as NULL even the first one when there is a date in the XML. Please help!
XML is case sensitive. Try is with:
MD.CD.value('(Value)[1]', 'DATE') AS 'CriticalDate',

bulk insert and parse a complex XML file into several tables

I have the following sql stored procedure to bulk insert and parse an xml file and insert its data into several tables in a database.
The sql below works, however its inserting duplicate records into the #questions table and the #cards table.
Any help on this would be much appreciated. Thanks in advance.
Here is the XML file:
<?xml version="1.0" encoding="UTF-8"?>
<Users>
<User>
<UserInfo>
<Id>0001</Id>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Email>Doejk#net.com</Email>
</UserInfo>
<Questions>
<Question>
<Id>1</Id>
<AnswerId>1</AnswerId>
</Question>
<Question>
<Id>2</Id>
<AnswerId>3</AnswerId>
</Question>
</Questions>
<Cards>
<Card>
<Id>1234</Id>
<Type>Digital</Type>
<Status>Active</Status>
</Card>
<Card>
<Id>1334</Id>
<Type>Physical</Type>
<Status>Not Active</Status>
</Card>
</Cards>
</User>
<User>
<UserInfo>
<Id>0002</Id>
<FirstName>Mary</FirstName>
<LastName>Doe</LastName>
<Email>Doem#net.com</Email>
</UserInfo>
<Questions>
<Question>
<Id>3</Id>
<AnswerId>6</AnswerId>
</Question>
<Question>
<Id>4</Id>
<AnswerId>7</AnswerId>
</Question>
</Questions>
<Cards>
<Card>
<Id>3333</Id>
<Type>Digital</Type>
<Status>Active</Status>
</Card>
<Card>
<Id>4444</Id>
<Type>Physical</Type>
<Status>Active</Status>
</Card>
</Cards>
</User>
</Users>
Here is SQL code
/*************************************************************************
-- CREATE TEMP TABLES --
**************************************************************************/
CREATE TABLE #XMLDATA
(RecordId int IDENTITY(1,1) NOT NULL,
XmlData xml NOT NULL)
CREATE TABLE #USERS
(UserID int null,
firstname varchar(50) null,
lastname varchar(50) null,
email varchar(50) null)
CREATE TABLE #CARDS
(CardId int null,
userid int null,
card_type varchar(50) null,
card_status varchar(50) null)
CREATE TABLE #QUESTIONS
(UserID int null,
Question_ID int null,
Answer_ID int null)
/*************************************************************************
-- LOAD THE WHOLE XML AS SINGLE BLOB --
**************************************************************************/
INSERT INTO #XMLDATA(XmlData)
SELECT *
FROM OPENROWSET(
BULK 'c:\users.xml', SINGLE_BLOB)
/*************************************************************************
-- INSERT USERS --
**************************************************************************/
INSERT INTO #USERS
(userid, firstname, lastname, email)
SELECT href.value('(Id/text())[1]', 'integer'),
href.value('(FirstName/text())[1]', 'varchar(50)'),
href.value('(LastName/text())[1]', 'varchar(50)'),
href.value('(Email/text())[1]', 'varchar(30)'),
FROM #XMLDATA CROSS APPLY
XmlData.nodes('Users') AS userinfo(href)
/*************************************************************************
-- INSERT QUESTIONS INFORMATION --
**************************************************************************/
INSERT INTO #QUESTIONS
(UserId, Question_ID, Answer_ID)
SELECT sref.value('(Id/text())[1]', 'integer'),
qref.value('(Id/text())[1]', 'integer'),
qref.value('(AnswerId/text())[1]', 'integer')
FROM #XMLDATA CROSS APPLY
XmlData.nodes('Users/Questions/Question') AS Ques(qref) CROSS APPLY
XmlData.nodes('Users') AS userinf(sref)
/*************************************************************************
-- INSERT CARD INFORMATION --
**************************************************************************/
INSERT INTO #CARDS
(userid, card_id, card_type,card_status)
SELECT sref.value('(Id/text())[1]', 'integer'),
cref.value('(Id/text())[1]', 'integer'),
cref.value('(Type/text())[1]', 'varchar(50)'),
cref.value('(Status/text())[1]', 'varchar(50)')
FROM #XMLDATA CROSS APPLY
XmlData.nodes('/Users/Cards/Card') AS cardlist(cref) CROSS APPLY
XmlData.nodes('/Users') AS userinf(sref)
I'm not sure what your CROSS JOIN is about.
Here is some shredding.
Tip: Comment out the INSERT portion and just do the SELECT portion until you get those tweaked correctly.
DECLARE #data XML;
SET #data =
N'
<Users>
<User>
<UserInfo>
<Id>0001</Id>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Email>Doejk#net.com</Email>
</UserInfo>
<Questions>
<Question>
<Id>1</Id>
<AnswerId>1</AnswerId>
</Question>
<Question>
<Id>2</Id>
<AnswerId>3</AnswerId>
</Question>
</Questions>
<Cards>
<Card>
<Id>1234</Id>
<Type>Digital</Type>
<Status>Active</Status>
</Card>
<Card>
<Id>1334</Id>
<Type>Physical</Type>
<Status>Not Active</Status>
</Card>
</Cards>
</User>
<User>
<UserInfo>
<Id>0002</Id>
<FirstName>Mary</FirstName>
<LastName>Doe</LastName>
<Email>Doem#net.com</Email>
</UserInfo>
<Questions>
<Question>
<Id>3</Id>
<AnswerId>6</AnswerId>
</Question>
<Question>
<Id>4</Id>
<AnswerId>7</AnswerId>
</Question>
</Questions>
<Cards>
<Card>
<Id>3333</Id>
<Type>Digital</Type>
<Status>Active</Status>
</Card>
<Card>
<Id>4444</Id>
<Type>Physical</Type>
<Status>Active</Status>
</Card>
</Cards>
</User>
</Users>';
SELECT T.myEntity.value('(Id)[1]', 'VARCHAR(20)')
, T.myEntity.value('(FirstName)[1]', 'VARCHAR(20)')
, T.myEntity.value('(LastName)[1]', 'VARCHAR(20)')
, T.myEntity.value('(Email)[1]', 'VARCHAR(20)')
FROM #data.nodes('Users/User/UserInfo') AS T(myEntity);
SELECT
T.myEntity.value('(../../UserInfo/Id)[1]', 'VARCHAR(20)')
, T.myEntity.value('(Id)[1]', 'INT')
, T.myEntity.value('(AnswerId)[1]', 'INT')
FROM #data.nodes('Users/User/Questions/Question') AS T(myEntity);
SELECT
T.myEntity.value('(../../UserInfo/Id)[1]', 'VARCHAR(20)')
, T.myEntity.value('(Id)[1]', 'INT')
, T.myEntity.value('(Type)[1]', 'VARCHAR(20)')
, T.myEntity.value('(Status)[1]', 'VARCHAR(20)')
FROM #data.nodes('Users/User/Cards/Card') AS T(myEntity);
CREATE TABLE #XMLDATA
(RecordId int IDENTITY(1,1) NOT NULL,
XmlData xml NOT NULL)
CREATE TABLE #USERS
(UserID int null,
firstname varchar(50) null,
lastname varchar(50) null,
email varchar(50) null)