4

I am just trying to get the JobID attribute from some XML using the following script. Is there a better way to do this?

    PROCEDURE [dbo].[spProcessJobXML]
@XMLPACKET as nvarchar(MAX) --<Root><Job JobID='2'></Root>
AS
-- Declare XML doc handle
declare @docHandle int
Declare @jobid nvarchar(3);
Declare @parentid int;
declare @testInt int;

-- Create XML Doc
exec sp_xml_preparedocument @docHandle OUTPUT, @XMLPACKET


if exists (
SELECT * FROM tempdb.sys.tables WHERE [name] like '#tempTable%'
)
DROP TABLE tempdb.#tempTable;


SELECT * INTO #tempTable FROM  OPENXML (@docHandle, '/Root/Job')
Select top 1 @parentid = #tempTable.id from #tempTable where #tempTable.localname like 'JobID';
--select * from #tempTable;
Select top 1 @jobid = #tempTable.[text] from #tempTable where  #tempTable.parentid = @parentid;
SET @testInt = CAST(@jobid AS int) 

Thanks

Bert
  • 80,741
  • 17
  • 199
  • 164
nomi
  • 431
  • 1
  • 5
  • 12

2 Answers2

3

If you are on SQL Server 2005 or later you can use the XML data type instead.

declare @testInt int
declare @XMLPACKET as xml 
set @XMLPACKET = '<Root><Job JobID="2"/></Root>'

set @testInt = @XMLPACKET.value('(/Root/Job)[1]/@JobID', 'int')
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
0

Add a "with" clause to your openxml statement.

SELECT JobID 
FROM  
OPENXML (@docHandle, '/Root/Job') with (JobID int '@JobID')
Bert
  • 80,741
  • 17
  • 199
  • 164