使用表1 [sql-server]的参考从表2获取数据

时间:2018-03-21 14:27:09

标签: sql sql-server xml

[TRN_ID]是另一个表的id,如何从该表中获取数据并在xml输出中显示此数据

  SELECT TOP (1) [ECB_ID] as Id
 ,[ECB_PASSWORD_GENERATED] as clave
 ,[ECB_CONSECUTIVE_NUMBER] as consecutive
 ,[ECB_BILL_DATE] as  date
 ,[TRN_ID] <- id of other table
 ,[QRC_ID]
  FROM [crdx_COREDev1].[dbo].[ECB_ELECTRONICBILL]
  FOR XML PATH ('FE')

输出示例

 <FE>
  <id>1</id>
  <pass>0</pass>
  <CONSECUTIVE>0</CONSECUTIVE>
  ....
   --These are the data from the other table.
  <emisor>
   <name>1</name>
   <Copany>myCompa</Company>
   ...
   ...
  </emisor>
 </FE>

总之,我有一个表1具有不同的数据,其中一些数据是对其他表的引用,使用该引用我想从表2中获取数据

1 个答案:

答案 0 :(得分:0)

您可以使用与FOR XML链接的嵌套TRN_ID

SELECT TOP (1) 
    [ECB_ID] as Id,
    [ECB_PASSWORD_GENERATED] as clave,
    [ECB_CONSECUTIVE_NUMBER] as consecutive,
    [ECB_BILL_DATE] as  date,
    [TRN_ID],
    [QRC_ID],
    (
        SELECT
            N.YourWantedColumn
        FROM
            YourOtherTable AS N
        WHERE
            E.TRN_ID = N.TRN_ID -- I'm guessing it's called N.TRN_ID
        FOR XML
            PATH ('emisor'), TYPE
    )
FROM 
    [crdx_COREDev1].[dbo].[ECB_ELECTRONICBILL] AS E
FOR XML 
    PATH ('FE')