החזרת ערך שדה מהרשומה הראשונה או האחרונה בערכת התוצאות המוחזרת על-ידי שאילתה.
תחביר
First(expr)
Last(expr)
מציין המיקום expr מייצג ביטוי מחרוזת המזהה את השדה אשר מכיל את הנתונים בהם ברצונך להשתמש, או ביטוי המבצע חישוב באמצעות הנתונים באותו שדה. אופרנדים תחת expr יכולים לכלול את שמו של שדה בטבלה, קבוע או פונקציה (היכולה להיות פנימית או מוגדרת על-ידי המשתמש אך לא אחת מפונקציות הצבירה האחרות של SQL).
הערות
הפונקציות First ו- Last דומות לפעולות השירות MoveFirst ו- MoveLast של אובייקט Recordset של DAO. פעולות אלה פשוט מחזירות את ערכו של שדה מסויים ברשומה הראשונה או האחרונה, בהתאמה, בערכת התוצאות המוחזרת על-ידי שאילתה. מאחר שרשומות בדרך כלל אינן מוחזרות בסדר מסויים (אלא אם השאילתה כוללת פסוקית ORDER BY), הרשומות המוחזרות על-ידי פונקציות אלה יהיו שרירותיות.
דוגמאות לפונקציות First, Last
דוגמה זו עושה שימוש בטבלה Employees כדי להחזיר את הערכים מתוך השדה LastName ברשומה הראשונה וברשומה האחרונה המוחזרות מהטבלה.
הדוגמה שולחת קריאה אל הפרוצדורה EnumFields, אותה באפשרותך למצוא בדוגמה למשפט SELECT.
Sub FirstLastX1()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Return the values from the LastName field of the
' first and last records returned from the table.
Set rst = dbs.OpenRecordset("SELECT " _
& "First(LastName) as First, " _
& "Last(LastName) as Last FROM Employees;")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the
' Recordset. Pass the Recordset object and desired
' field width.
EnumFields rst, 12
dbs.Close
End Sub
הדוגמה הבאה משווה בין שימוש בפונקציות First ו- Last לבין שימוש בפונקציות Min ו- Max כדי למצוא את תאריך הלידה המוקדם ביותר והמאוחר ביותר של עובדים בטבלה Employees.
Sub FirstLastX2()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Find the earliest and latest birth dates of
' Employees.
Set rst = dbs.OpenRecordset("SELECT " _
& "First(BirthDate) as FirstBD, " _
& "Last(BirthDate) as LastBD FROM Employees;")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the
' Recordset. Pass the Recordset object and desired
' field width.
EnumFields rst, 12
Debug.Print
' Find the earliest and latest birth dates of
' Employees.
Set rst = dbs.OpenRecordset("SELECT " _
& "Min(BirthDate) as MinBD," _
& "Max(BirthDate) as MaxBD FROM Employees;")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the
' Recordset. Pass the Recordset object and desired
' field width.
EnumFields rst, 12
dbs.Close
End Sub
|