简体   繁体   English

使用变量从 XML 节点中提取值

[英]Extracting Values from XML node using variable

I have the following sql query and want to get the values of only the CURCVY node values from 1-4 so I can insert each node to a table.我有以下 sql 查询,并希望仅获取 1-4 的 CURCVY 节点值,以便我可以将每个节点插入到表中。 but all it inserts are the node names但它插入的只是节点名称

   DECLARE
   @MYARRAY table (TEMPCOL nvarchar(50)),
   @tvar char(100),
   @cnt INT = 1,
   @cnt_total int =5, 
   @xmldata xml='<NewDataSet>
   <ROWS>
    <POLIAGIN>PRE-AUTHORIZED</POLIAGIN>
    <CURCVY01>0.00</CURCVY01>
    <CURCVY02>253.00</CURCVY02>
    <CURCVY03>1523.50</CURCVY03>
    <CURCVY04>2815.50</CURCVY04>
    <CURCVY05>4129.00</CURCVY05>
  </ROWS>
</NewDataSet>'

WHILE @cnt < @cnt_total
BEGIN
set @tvar = 'CURCVY0'+ cast(@cnt as char(5))
   EXEC sp_insert_to_my_table @xmldata.query('NewDataSet/ROWS/*').value('(sql:variable("@tvar"))[1]','nvarchar(max)') 
   SET @cnt = @cnt + 1; 
END;

this is what the sp does这就是 sp 所做的

--sp_insert_to_my_table

declare
@amount as vachar(max)

insert into myTable (column1)
values (@amount)

UPDATE更新

I've tried the following method and now I get null values我尝试了以下方法,现在我得到了 null 个值

EXEC sp_insert_to_my_table @xmldata.value('(/NewDataSet/ROWS/*[local-name() = sql:variable("@tvar")])[1]','nvarchar(max)')

Guessing what you need.猜猜你需要什么。

SQL SQL

DECLARE @maxValue CHAR(2) = '04'
, @xmldata XML = 
N'<NewDataSet>
   <ROWS>
    <CURCVY01>0.00</CURCVY01>
    <CURCVY02>253.00</CURCVY02>
    <CURCVY03>1523.50</CURCVY03>
    <CURCVY04>2815.50</CURCVY04>
    <CURCVY05>4129.00</CURCVY05>
  </ROWS>
</NewDataSet>';

SELECT c.value('text()[1]', 'decimal(10,2)') AS Result
FROM @xmldata.nodes('/NewDataSet/ROWS/*[substring(local-name(.),7,2) le sql:variable("@maxValue")]') AS t(c)

Output Output

+---------+
| Result  |
+---------+
|    0.00 |
|  253.00 |
| 1523.50 |
| 2815.50 |
+---------+

Looks like this is the code you need:看起来这是您需要的代码:

DECLARE
  @maxValue int = 4,
  @xmldata xml='
<NewDataSet>
   <ROWS>
    <POLIAGIN>PRE-AUTHORIZED</POLIAGIN>
    <CURCVY01>0.00</CURCVY01>
    <CURCVY02>253.00</CURCVY02>
    <CURCVY03>1523.50</CURCVY03>
    <CURCVY04>2815.50</CURCVY04>
    <CURCVY05>4129.00</CURCVY05>
  </ROWS>
</NewDataSet>';

INSERT myTable (column1)
SELECT x.CURCVY.value('text()[1]','decimal(18,5)')
FROM @xmldata.nodes('NewDataSet/ROWS/*[substring(local-name(), 1, 6) = "CURCVY"][position() <= 4]') x(CURCVY);

Note how the position() predicate is separate, therefore it only begins counting after the substring() has filtered.请注意position()谓词是如何分开的,因此它仅在substring()过滤后才开始计数。

db<>fiddle 数据库<>小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM