我需要了解以下MS SQL语句(SELECT FROM VALUES)

时间:2019-06-14 13:36:32

标签: sql-server

我对MS SQL还是很陌生,但是现在我不得不做很多工作。我需要了解这里发生的情况:

    BEGIN TRANSACTION loadHalfdayAbsences;
    INSERT INTO @halfDayAbsences
    ([AbsencePart], 
     [AbsenceId], 
     [DeleteDate], 
     [LastChangeDate]
    )
           SELECT CASE ap.AbsencePart
                      WHEN 1
                      THEN a.AbsenceStart
                      WHEN 3
                      THEN a.AbsenceEnd
                      ELSE CASE
                               WHEN a.AbsenceStartHalfDay = 1
                               THEN DATEADD(DAY, 1, a.AbsenceStart)
                               ELSE a.AbsenceStart
                           END
                  END AS newEnd,
                  CASE ap.AbsencePart
                      WHEN 1
                      THEN 0.50
                      WHEN 2
                      THEN 1.00
                      WHEN 3
                      THEN 0.50
                  END AS newDuration, 
                  [ap].[AbsencePart], 
                  [a].[AbsenceId], 
                  [a].[EmployeeId], 
           FROM
           (
               SELECT AbsencePart
               FROM(VALUES(1), (2), (3)) AS t(AbsencePart)
           ) AS ap
           INNER JOIN dwh.Absence AS a ON 1 = 1
           WHERE AbsenceType IN
           (
               SELECT AbsenceType
               FROM @AbsenceType4TimeTac
           )

特别是:

           FROM
           (
               SELECT AbsencePart
               FROM(VALUES(1), (2), (3)) AS t(AbsencePart)
           ) AS ap
           INNER JOIN dwh.Absence AS a ON 1 = 1
           WHERE AbsenceType IN
           (
               SELECT AbsenceType
               FROM @AbsenceType4TimeTac
           )
  • 这部分做什么?
  • VALUES在这里为我做什么?
  • 数据发生了什么?
  • 是否已选择它,但仅其中有1、2或3的字段?或VALUES发生了什么?

感谢您提前进行任何输入:)

2 个答案:

答案 0 :(得分:4)

该部分

FROM (VALUES(1), (2), (3)) AS t(AbsencePart)

just是一个内联表,在名为AbsensePart的列中由1到3的三个值组成。您可能还使用了以下语法:

FROM
(
    SELECT 1 AS AbsencePart UNION ALL
    SELECT 2 UNION ALL
    SELECT 3
) t

答案 1 :(得分:1)

被称为表值构造器。当您在表中有想要的已知值列表时,可使用它代替临时表之类的东西。您可以阅读有关here的更多信息。