Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to understand the following MS SQL statement ( SELECT FROM VALUES)

Tags:

sql-server

I am pretty new to MS SQL but I am having to work with it a lot now. I need to understand what is going on here:

    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
           )

Particularly:

           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
           )
  • What does this part do?
  • What do the VALUES do here for me?
  • What happens to the data?
  • Is it being selected, but only fields where there is either a 1, a 2 or a 3 in there? Or what is going on with VALUES?

Thanks for any input in advance :)

like image 397
MrMee Avatar asked Mar 03 '23 20:03

MrMee


1 Answers

The portion

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

just is an inline table consisting of three values, 1 through 3, in a column called AbsensePart. You could have also used the following syntax:

FROM
(
    SELECT 1 AS AbsencePart UNION ALL
    SELECT 2 UNION ALL
    SELECT 3
) t
like image 106
Tim Biegeleisen Avatar answered May 03 '23 07:05

Tim Biegeleisen