开发者

TSQL - use variables in OPENXML

开发者 https://www.devze.com 2023-03-26 10:58 出处:网络
Suppose I have a query like this - SELECT * FROM OPENXML(@i, \'/root/authors\', 2) WITH authors Now, I want to pass \'/root\' via a parameter/variable like -

Suppose I have a query like this -

SELECT * FROM 
    OPENXML(@i, '/root/authors', 2) 
        WITH authors

Now, I want to pass '/root' via a parameter/variable like -

DECLARE @nodeName varchar(MAX) ----> EDI开发者_Python百科T: Solution- Use fixed length instead of MAX
SET @nodeName = '/root'

and use @nodeName instead. Then concatenate the rest of the elements dynamically. I am getting error just by using @nodeName in the OPENXML parameter.


Better to use the new XML type.

create proc [dbo].[getLocationTypes](@locationIds XML,
@typeIds XML=null)
as  
begin  
set nocount on  


SELECT locationId, typeId
FROM xrefLocationTypes 
WHERE locationId 
IN (SELECT Item.value('.', 'int' )
FROM @locationIDs.nodes('IDList/ID') AS x(Item))
AND (typeId IN
 (SELECT Item.value('.', 'int' )
FROM @typeIds.nodes('IDList/ID') AS x(Item)))
ORDER BY 1, 2

end  

And then you would call this like:

EXECUTE dbo.getLocationTypes '<IDList><ID>1</ID><ID>3</ID></IDList>', 
'<IDList><ID>200</ID><ID>300</ID><ID>400</ID></IDList>'    


I tried the following in SQL 2008 R2 and it works fine.

DECLARE @idoc int
DECLARE @doc varchar(1000)
SET @doc ='
<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
   <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
      <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
      <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
   </Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
   <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
      <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
   </Order>
</Customer>
</ROOT>'
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
-- Execute a SELECT statement that uses the OPENXML rowset provider.
DECLARE @NodeName VARCHAR(100)
SET @NodeName = '/ROOT/Customer'
SELECT    *
FROM       OPENXML (@idoc, @NodeName,1)
            WITH (CustomerID  varchar(10),
                  ContactName varchar(20))

It could be that other versions of SQL only support the use of NVARCHAR as a parameter, not VARCHAR.

I hope this help.

0

精彩评论

暂无评论...
验证码 换一张
取 消