I\'m trying to insert rows into a table using a select from XML. I think I\'m close. Where am I going wrong?
declare @xmldata xml;
set @xmldata = \'
To address the question of why the need for the positional predicate (i.e., [1]) within the XQuery string literal, like @pbz indicated, a singleton is required and therefore must be guaranteed. To add more substance to @pbz's answer, see below.
Per Microsoft's SQL Docs:
In the following example, an XML instance is stored in a variable of xml type. The value() method retrieves the ProductID attribute value from the XML. The value is then assigned to an int variable.
DECLARE @myDoc xml DECLARE @ProdID int SET @myDoc = '' SET @ProdID = @myDoc.value('(/Root/ProductDescription/@ProductID)[1]', 'int' ) SELECT @ProdID 1 year parts and labor 3 year parts and labor extended maintenance is available Value 1 is returned as a result.
Although there is only one ProductID attribute in the XML instance, the static typing rules require you to explicitly specify that the path expression returns a singleton. Therefore, the additional
[1]is specified at the end of the path expression. For more information about static typing, see XQuery and Static Typing.
Following that link then leads us to:
As mentioned earlier, type inference frequently infers a type that is broader than what the user knows about the type of the data that is being passed. In these cases, the user has to rewrite the query. Some typical cases include the following:
...
- The type infers a higher cardinality than what the data actually contains. This occurs frequently, because the xml data type can
contain more than one top-level element, and an XML schema collection cannot constrain this. In order to reduce the static type and
guarantee that there is indeed at most one value being passed, you
should use the positional predicate[1]. For example, to add 1 to the value of the attribute c of the element b under the top-level a
element, you must write(/a/b/@c)[1]+1. Additionally, the DOCUMENT
keyword can be used together with an XML schema collection.