简体   繁体   English

使用T-SQL更新XML格式的列选择数据SQL表

[英]To update a column in XML Format Selecting data SQL Table using T-SQL

I have data in a SQL Table and I want to query some columns of the existing data in XML Format(using For XML ) or any best practice and then update the XML FOrmat into a column in the same table with XML datatype .If you notice the example below , the Node SALARY is not a column name and its a constant value. 我在SQL表中有数据,我想查询XML格式(使用For XML)或任何最佳做法的现有数据的某些列,然后将XML FOrmat更新为具有XML数据类型的同一表中的列。在下面的示例中,Node SALARY不是列名,而是一个常数。 ( In this sample there are 2 AMT columns as AMT1 and AMT2 which might vary as AMT3 sometimes) and accordingly the SALARY NODE Should also increment with the next number .If any one advice how to approach it would be of great help. (在此示例中,有2条AMT列,如AMT1和AMT2,有时可能会随着AMT3的不同而变化),因此,SALARY NODE也应随下一个数字递增。如果有任何建议如何使用它将非常有帮助。 The format of my data is : 我的数据格式为:


EMPNAME  YEAR     MONTH AMT1     AMT2
smith     2013     jan  5000     6000
Ray       2014     feb  4000     5000
Jones     2013     apr  6000     3000

the XML format I want is : 我想要的XML格式是:

<EMPLOYEE>
  <EMPNAME>Smith</EMPNAME>
  <SALARYDETAILS>
     <SALARY>1<SALARY>
     <AMOUNT>5000</AMOUNT>
     <SALARY>2<SALARY>
     <AMOUNT>6000</AMOUNT>
  </SALARYDETAILS>
</EMPLOYEE>
<EMPLOYEE>
      <EMPNAME>Ray</EMPNAME>
      <SALARYDETAILS>
         <SALARY>1<SALARY>
         <AMOUNT>4000</AMOUNT>
         <SALARY>2<SALARY>
         <AMOUNT>5000</AMOUNT>
      </SALARYDETAILS>
    </EMPLOYEE>

I tried the basic SQL like this but not sure how to add nodes in between which are not sql columns like 'SALARYDETAILS' 我尝试过这样的基本SQL,但不确定如何在其中添加不是'SALARYDETAILS'之类的sql列的节点

SELECT  EMPNAME ,AMT1,AMT2 FROM  EMPLOYEE
FOR XML RAW  (''), ROOT ('EMPLOYEE') - This SQL also gives error as Empty Tags cannot be passed 

. Thanks Mikael, That was very helpful ,I could get the idea on specifying dummy nodes , but the requirement is , the number of amount nodes might vary depending on data and so the SALARY node will also depend on that .. like for some records it could be just one AMT1, some might have 3 AMT columns.. so it could vary and accordingly and so the query has to be built dynamically . 谢谢Mikael,这非常有帮助,我可以得到指定虚拟节点的想法,但是要求是,数量的节点数可能会根据数据而有所不同,因此SALARY节点也将取决于此。可能只是一个AMT1,有些可能有3个AMT列..因此它可能有所不同,因此查询必须动态构建。 I could even use a stored procedure . 我什至可以使用存储过程。 Thanks .. 谢谢 ..

Hi , Any idea how to concatenate 2 xml variables in a Stored Procedure. 嗨,任何想法如何在存储过程中连接2个xml变量。

If I understand what you want you could just specify the salary nodes as constants in the query. 如果我了解您想要的内容,则只需在查询中将薪金节点指定为常量。

select E.EMPNAME,
       1      as 'SALARYDETAILS/SALARY',
       E.AMT1 as 'SALARYDETAILS/AMOUNT',
       2      as 'SALARYDETAILS/SALARY', 
       E.AMT2 as 'SALARYDETAILS/AMOUNT'
from EMPLOYEE as E
for xml path('EMPLOYEE')

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

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