从sql中选择(外部应用)

时间:2016-03-30 07:47:29

标签: sql sql-server tsql

在Sql中,您可以执行以下操作

select 1, 2, 3

这是不使用'来自'的select语句。我刚刚拿起如何使用外部应用。

通常你会做这样的外部申请:

  SELECT * FROM Department D 
OUTER APPLY 
   ( 
   SELECT * FROM Employee E 
   WHERE E.DepartmentID = D.DepartmentID 
   ) A

我想知道是否有办法在不使用上面提到的from语句的情况下执行此操作?

For example: 
 Select 1,
        2, 
 OUTER APPLY 
           ( 
              SELECT * FROM Employee E 
             WHERE E.DepartmentID = D.DepartmentID 
           ) E         OUTER APPLY 
   ( 
   SELECT * FROM Employee_Service serv 
   WHERE E.DepartmentID = serv.DepartmentID 
   ) S

2 个答案:

答案 0 :(得分:3)

这可能接近您所寻找的内容:

 SELECT *
 FROM ( Select 1 AS DepartmentID UNION ALL SELECT 2 ) AS D
 OUTER APPLY 
 ( 
     SELECT * 
     FROM Employee E 
     WHERE E.DepartmentID = D.DepartmentID 
 ) E         
 OUTER APPLY 
 (
     SELECT * 
     FROM Employee_Service serv 
     WHERE E.DepartmentID = serv.DepartmentID 
 ) S

或使用VALUES

 SELECT *
 FROM ( VALUES (1), (2) ) AS D(DepartmentID)
 OUTER APPLY 
 ( 
     SELECT * 
     FROM Employee E 
     WHERE E.DepartmentID = D.DepartmentID 
 ) E         
 OUTER APPLY 
 (
     SELECT * 
     FROM Employee_Service serv 
     WHERE E.DepartmentID = serv.DepartmentID 
 ) S

答案 1 :(得分:1)

如果您想要多列的单列,那么

试试这个

SELECT *
FROM (Select 1 UNION ALL SELECT 2) AS D(DepartmentID)
OUTER APPLY 
( 
    SELECT * FROM Employee E 
    WHERE E.DepartmentID = D.DepartmentID 
) E         
OUTER APPLY 
( 
    SELECT * FROM Employee_Service serv 
    WHERE E.DepartmentID = serv.DepartmentID 
) S

如果您想要单行多列,那么

试试这个

SELECT *
FROM (Select 1 DepartmentID,2 DepartmentName,..) AS D
OUTER APPLY 
( 
    SELECT * FROM Employee E 
    WHERE E.DepartmentID = D.DepartmentID 
) E         
OUTER APPLY 
( 
    SELECT * FROM Employee_Service serv 
    WHERE E.DepartmentID = serv.DepartmentID 
) S