I have a table with a XML column and appreciate any help how to get all data from that columns. This is the simplified sample, but should help to understand my issue. I can get all Employee data but I have no idea how to include DeptID data for each return row.
CREATE TABLE #Deductions (RecordID int identity(1,1) not null primary key, FirmID int, XML_Data xml not null)
DECLARE @TempXML xml
SET @TempXML =
'<Deductions startDate="01/01/2011" endDate="03/31/2011">
<Dept DeptID="561" TotalEmplyees="2" TotalDeductions="12345.55">
<Employee ID="5611"
Amount="1234.56"
EnrollDate="10/22/1999" />
<Employee ID="5612"
Amount="123.57"
EnrollDate="11/23/1997" />
</Dept>
<Dept DeptID="562" TotalEmplyees="3" TotalDeductions="54321.99">
<Employee ID="5621"
Amount="12.56"
EnrollDate="10/22/1999" />
<Employee ID="5622"
Amount="1.57"
EnrollDate="10/22/1995" />
<Employee ID="5623"
Amount="1.57"
EnrollDate="12/22/1991" />
</Dept>
</Deductions>'
INSERT INTO #Deductions(FirmID, XML_Data) VALUES(12345, @TempXML)
SELECT d.RecordID, d.FirmID,
R.e.value('@ID', 'int') ID,
R.e.value('@Amount', 'decimal(29,2)') Amount,
R.e.value('@EnrollDate', 'datetime') EnrollDate
FROM #Deductions d WITH (NOLOCK)
CROSS APPLY XML_Data.nodes ('/Deductions/Dept/Employee') R(e)
WHERE d.FirmID = 12345
DROP TABLE #Deductions
CREATE TABLE #Deductions (RecordID int identity(1,1) not null primary key, FirmID int, XML_Data xml not null)
DECLARE @TempXML xml
SET @TempXML =
'<Deductions startDate="01/01/2011" endDate="03/31/2011">
<Dept DeptID="561" TotalEmplyees="2" TotalDeductions="12345.55">
<Employee ID="5611"
Amount="1234.56"
EnrollDate="10/22/1999" />
<Employee ID="5612"
Amount="123.57"
EnrollDate="11/23/1997" />
</Dept>
<Dept DeptID="562" TotalEmplyees="3" TotalDeductions="54321.99">
<Employee ID="5621"
Amount="12.56"
EnrollDate="10/22/1999" />
<Employee ID="5622"
Amount="1.57"
EnrollDate="10/22/1995" />
<Employee ID="5623"
Amount="1.57"
EnrollDate="12/22/1991" />
</Dept>
</Deductions>'
INSERT INTO #Deductions(FirmID, XML_Data) VALUES(12345, @TempXML)
SELECT d.RecordID, d.FirmID,
R.e.value('@ID', 'int') ID,
R.e.value('@Amount', 'decimal(29,2)') Amount,
R.e.value('@EnrollDate', 'datetime') EnrollDate
FROM #Deductions d WITH (NOLOCK)
CROSS APPLY XML_Data.nodes ('/Deductions/Dept/Employee') R(e)
WHERE d.FirmID = 12345
DROP TABLE #Deductions