使用内部选择条件从同一个表中插入两个选择语句的选择

时间:2017-07-24 20:19:31

标签: sql sql-server

INSERT INTO Training
( 
     TrainingID
    ,EmployeeID 
    ,TrainingEmployeeStatusID
    ,TrainingSessionID
    ,DepartmentID
    ,LastModified
    ,RevisionNum
) 

SELECT        
       (SELECT TrainingID from TrainingGlobal.TrainingInformation
        WHERE TrainingDesc = 'A First Value') 
      , FirmEmployeeID
      , 5
      , TrainingSessionID
      , DepartmentID
      , GETDATE()
      , 1

UNION ALL SELECT        
       (SELECT TrainingID from TrainingGlobal.TrainingInformation
        WHERE TrainingDesc = 'Another Value') 
      , FirmEmployeeID
      , 5
      , TrainingSessionID
      , DepartmentID
      , GETDATE()
      , 1


   From #ATempTable
        WHERE DepartmentID IN ( SELECT DepartmentID from TrainingGlobal.DepartmentIDs) 
        AND   FirmEmployeeID IN (SELECT EmployeeID from TrainingGlobal.EmployeeIDS)

我的问题是,如果可以在Insert Into中有两个select语句,其中select语句从同一个表中选择,但是在每个新表项中更改内部选择的条件。

因为在每个select语句的第一行中,WHERE子句具有不同的条件,但信息都来自一个临时表。

我正在使用MS-SQL 2016

1 个答案:

答案 0 :(得分:1)

JOIN似乎更简单:

SELECT ti.TrainingInformation
      FirmEmployeeID,
      (CASE WHEN ti.TrainingDesc = 'A First Value' THEN 5 ELSE 6 END),
      TrainingSessionID, DepartmentID, GETDATE(), 1
FROM #ATempTable a CROSS JOIN
     (SELECT ti.*
      FROM Training.TrainingInformation ti
      WHERE TrainingDesc IN ('A First Value', 'Another Value')
     ) ti;