Reputation: 43
I have created a stored procedure that reads XML data as its input. I am having two issues that I am hoping someone can help with.
Issue 1: When I execute the stored procedure, I only get back the first value for AccountType
(9). I am expecting/wanting to get back all values for AccountType
.
Issue 2: Once I have fixed the above issue I would like to use values from AccountType
to select users from another table e.g. dbo.UserData
What I have tried:
I saw this on another SO post that you can debug but I am not sure exactly how to use this or what it's doing.
select col.query('.') as Debug
XML:
<root>
<From>4</From>
<AccountType>9</AccountType>
<AccountType>5</AccountType>
<AccountType>6</AccountType>
<AccountType>7</AccountType>
<AccountType>5</AccountType>
<AccountType>4</AccountType>
<AccountType>1</AccountType>
<AccountType>15</AccountType>
<AccountType>16</AccountType>
<AccountType>1</AccountType>
<AccountType>ivs</AccountType>
<AccountType>10</AccountType>
<AccountType>12</AccountType>
<AccountType>11</AccountType>
<AccountType>tfs</AccountType>
<AccountType>vsa</AccountType>
<AccountType>13</AccountType>
<AccountType>14</AccountType>
<GroupID>1</GroupID>
<GroupID>5</GroupID>
</root>
Stored procedure:
CREATE PROCEDURE dbo.UserSelect
@XMLInput XML
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT
'AccountType' = x.v('AccountType[1]', 'nvarchar(2)')
FROM
@XMLInput.nodes('/root') AS x(v)
END
Execution of stored procedure:
DECLARE @XML as XML
SET @XML = '<root>
<From>4</From>
<AccountType>9</AccountType>
<AccountType>5</AccountType>
<AccountType>6</AccountType>
<AccountType>7</AccountType>
<AccountType>5</AccountType>
<AccountType>4</AccountType>
<AccountType>1</AccountType>
<AccountType>15</AccountType>
<AccountType>16</AccountType>
<AccountType>1</AccountType>
<AccountType>ivs</AccountType>
<AccountType>10</AccountType>
<AccountType>12</AccountType>
<AccountType>11</AccountType>
<AccountType>tfs</AccountType>
<AccountType>vsa</AccountType>
<AccountType>13</AccountType>
<AccountType>14</AccountType>
<GroupID>1</GroupID>
<GroupID>5</GroupID>
</root>'
EXEC dbo.UserSelect @XML
Upvotes: 0
Views: 998
Reputation: 27224
You were close, but you needed to specify the 'AccountType' node in the nodes
function. And then use the value
function to get the value.
select distinct x.v.[value]('.','nvarchar(2)') AccountType
from @XML.nodes('/root/AccountType') x(v)
In an ITVF (Inline Table Valued Function) it looks like:
create function dbo.GetAccountTypeFromXML
(
@Xml xml
)
returns table
return
select distinct x.v.[value]('.','nvarchar(2)') AccountType
from @XML.nodes('/root/AccountType') x(v)
Which can then be used as, for example:
select *
from dbo.UserData
where AccountType in (select AccountType from dbo.GetAccountTypeFromXML(@Xml))
Upvotes: 1