SQL server与子表左键联接并获取表名

SQL server与子表左键联接并获取表名,sql,sql-server,Sql,Sql Server,假设我们有一个表工具,其子表Equity和Bond具有外键InstrumentId。每个仪器在一个子表中都有一个唯一的记录 是否可以使用左联接创建一个视图,以查看包含记录所在表名的列的所有仪器 SELECT Instrument.InstrumentId, Instrument.Name, ***CHILD_TABLE_NAME*** FROM Instrument LEFT OUTER JOIN Equity ON Equity.In

假设我们有一个表工具,其子表Equity和Bond具有外键InstrumentId。每个仪器在一个子表中都有一个唯一的记录

是否可以使用左联接创建一个视图,以查看包含记录所在表名的列的所有仪器

SELECT        Instrument.InstrumentId, Instrument.Name, ***CHILD_TABLE_NAME***
FROM          Instrument
LEFT OUTER JOIN
              Equity ON Equity.InstrumentId = Instrument.InstrumentId 
LEFT OUTER JOIN
              Bond ON SBond.InstrumentId = Instrument.InstrumentId 
另一种方法是生成内部联接的并集:

SELECT instrumentId, Name, instrumentType 
FROM
(SELECT Instrument.instrumentId, Name, 'Equity' as instrumentType FROM dbo.Equity inner join Instrument on Instrument.InstrumentId = Equity.InstrumentId
UNION
SELECT Instrument.instrumentId, Name, 'Bond' as instrumentType from dbo.Bond inner join Instrument on Instrument.InstrumentId = Bond.InstrumentId) u

使用
大小写
表达式:

SELECT i.InstrumentId, i.Name, 
       (CASE WHEN e.InstrumentId IS NOT NULL THEN 'Equity'
             WHEN b.InstrumentId IS NOT NULL THEN 'Bond'
        END) as which_table
FROM Instrument i LEFT OUTER JOIN
     Equity e
     ON e.InstrumentId = i.InstrumentId LEFT OUTER JOIN
     Bond b
     ON b.InstrumentId = i.InstrumentId ;
注意:这是第一次匹配。如果两者都需要:

SELECT i.InstrumentId, i.Name, 
       ((CASE WHEN e.InstrumentId IS NOT NULL THEN 'Equity' ELSE '' END) + 
        (CASE WHEN b.InstrumentId IS NOT NULL THEN 'Bond' ELSE '' END)
       ) as which_table
FROM Instrument i LEFT OUTER JOIN
     Equity e
     ON e.InstrumentId = i.InstrumentId LEFT OUTER JOIN
     Bond b
     ON b.InstrumentId = i.InstrumentId ;
编辑
我正在添加缺少的END

一个选项是像这样在连接中包括表名

SELECT i.InstrumentId, 
       i.Name, 
       e.TableEquity,
       b.TableBond
FROM Instrument i 
  LEFT OUTER JOIN (select 'Equity' as TableEquity from Equity) e
    ON i.InstrumentId = e.InstrumentId 
  LEFT OUTER JOIN (select 'Bond' as TableBond from Bond) b
    ON i.InstrumentId = b.InstrumentId
@sofsntp编辑:将股权/债券合并到一列中

SELECT i.InstrumentId, 
       i.Name, 
       (ISNULL(e.TableEquity,'') + ISNULL(b.TableBond ,''))
FROM Instrument i 
  LEFT OUTER JOIN (select *, 'Equity' as TableEquity from Equity) e
   ON e.InstrumentId = i.InstrumentId 
 LEFT OUTER JOIN (select *, 'Bond' as TableBond  from StraightBond) b
   ON b.InstrumentId = i.InstrumentId

谢谢你会接受这个答案的。我修复了ELSE“”附近的语法问题)+