SlideShare a Scribd company logo
1 of 41
Presented by Steve Stedman
and Aaron Buma
Welcome
 Welcome to all those joining us remotely.
 For any questions via Google On Air Broadcasts, we will
address most of these at the end of the training.
 Training provided by Emergency Reporting
 http://EmergencyReporting.com
 Slides and sample code are available at:
 http://SteveStedman.com
Welcome Viewers From
 Bellingham, WA
 Salt Lake City, UT
 Glacier, WA
 St Louis, MO
 Gainesville, FL
 Honolulu, HI
 Portugal
 Chennai, India
 Belarus
 Bucharest
Live Broadcast
 Using Google On Air Broadcasts
 There is about a 40 to 50 second delay from live to what
you see.
 We are still learning how to properly use Google On Air
Broadcasts. Please be patient.
 Session will be available on my YouTube Channel about
an hour after the presentation ends.
 http://SteveStedman.com/YouTube
Questions
 We will have time for questions at the end of the session.
 Q&A available via Google On Air Hangout panel. Click the 3x3
grid icon near the top right, then select Q&A to see what people
are asking, or to ask your own question.
 When you ask a question, it shows up for us about 40 to 50
seconds delayed.
Agenda
 Date and Time Functions
 Logical Functions
 User Defined Functions
Presented by Steve Stedman
Date/Time Functions
GETDATE()
DATEPART()
DATEADD()
DATEDIFF()
_____FROMPARTS (2012)
EOMONTH (2012)
GETDATE
 Returns the current database system timestamp as
a datetime value without the database time zone
offset.
SELECT GETDATE();
DATEPART()
 Returns an integer that represents the specified
datepart of the specified date.
SELECT DATEPART(year, GETDATE());
 Date can be time, date, smalldatetime, datetime,
datetime2, or datetimeoffset.
DATEADD()
 Returns a specified date with the specified number
interval (signed integer) added to a specified datepart
of that date.
SELECT DATEADD(month, 1, GETDATE());
DATEDIFF()
 Returns the count (signed integer) of the specified datepart
boundaries crossed between the specified startdate and enddate.
SELECT DATEDIFF(year, '1/1/2015', GETDATE());
SELECT DATEDIFF(quarter, '1/1/2015', GETDATE());
SELECT DATEDIFF(month, '1/1/2015', GETDATE());
DATEFROMPARTS (2012)
DATEFROMPARTS ( year, month, day )
 Arguments
 Year Integer expression specifying a year.
 Month Integer expression specifying a month, from 1 to 12.
 Day Integer expression specifying a day.
 Always Year – Month – Day order independent of language
or location
TIMEFROMPARTS (2012)
TIMEFROMPARTS ( hour, minute, seconds, fractions,
precision )
 Arguments
 Hour Integer expression specifying hours.
 Minute Integer expression specifying minutes.
 Seconds Integer expression specifying seconds.
 Fractions Integer expression specifying fractions.
 Precision Integer literal specifying the precision of
the time value to be returned.
DATETIMEFROMPARTS (2012)
DATETIMEFROMPARTS ( year, month, day, hour, minute,
seconds, milliseconds )
 Arguments
 Year Integer expression specifying a year.
 Month Integer expression specifying a month.
 Day Integer expression specifying a day.
 Hour Integer expression specifying hours.
 Minute Integer expression specifying minutes.
 Seconds Integer expression specifying seconds.
 Milliseconds Integer expression specifying milliseconds.
DATETIME2FROMPARTS (2012)
DATETIME2FROMPARTS (year, month, day, hour, minute, seconds, fractions, precision)
 Arguments
 Year Integer expression specifying a year.
 Month Integer expression specifying a month.
 Day Integer expression specifying a day.
 Hour Integer expression specifying hours.
 Minute Integer expression specifying minutes.
 Seconds Integer expression specifying seconds.
 Fractions Integer expression specifying fractions.
 Precision Integer literal specifying the precision of the datetime2 value to be returned.
SMALLDATETIMEFROMPARTS (2012)
SMALLDATETIMEFROMPARTS(year,month,day,hour,minute)
 Same idea as the others….
DATETIMEOFFSETFROMPARTS (2012)
 DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute,
seconds, fractions, hour_offset, minute_offset, precision )
 hour_offset - Integer expression specifying the hour portion of the time
zone offset.
 minute_offset - Integer expression specifying the minute portion of the
time zone offset.
 Precision - Integer literal specifying the precision of the value to be
returned.
 Precision can be a value of 0 to 7 which specifies the precision of the
fractional part of the seconds.
EOMONTH (2012)
EOMONTH ( start_date [, month_to_add ] )
 Returns the last day of the month that contains the
specified date, with an optional offset.
 Arguments
 start_date Date expression specifying the date for which
to return the last day of the month.
 month_to_add Optional integer expression specifying
the number of months to add to start_date.
Date and Time Functions
Demo
Please Connect on LinkedIn
Steve Stedman
http://linkedin.com/in/stevestedman
Aaron Buma
https://www.linkedin.com/in/aaronbuma
Presented by Steve Stedman
Logical Functions
CASE
IIF (2012)
CHOOSE (2012)
COALESCE
CASE
 Evaluates a list of conditions and returns one of
multiple possible result expressions.
CASE WHEN Revenue > AverageRevenue
THEN 'Better Than Average'
ELSE 'Not Better'
END AS Ranking
CASE with multiple WHEN
SELECT CASE @corners
WHEN 1 THEN 'point'
WHEN 2 THEN 'line'
WHEN 3 THEN 'triangle'
WHEN 4 THEN 'square'
WHEN 5 THEN 'pentagon'
WHEN 6 THEN 'hexagon'
WHEN 7 THEN 'heptagon'
WHEN 8 THEN 'octagon'
ELSE NULL
END;
IIF (2012)
 Returns one of two values, depending on whether the
Boolean expression evaluates to true or false in SQL Server.
 This is similar to Excel or VB versions of IIF.
IIF(Revenue > AverageRevenue,
'Better Than Average',
'Not Better' ) AS Ranking
 What does IIF stand for? Immediate IF? Inline IF?
IIF Details
 Performance very similar between IIF and CASE
 IIF simplifies the code over using a CASE statement
 Can be nested up to 10 levels
 The true value and false value cannot both be NULL.
CHOOSE (2012)
 Function that returns the item at a specific index.
 CHOOSE(index, val_1, val_2, val_3, ...)
 If the index is greater than the number of values or less
than 1 it returns NULL
 Easier than CASE in some examples
CHOOSE – Example
COALESCE
 Similar to CASE, or CHOOSE, but returns the first
NON NULL value.
 Similar to ISNULL when using 2 parameters
COALESCE([Parent], 0)
 Will accommodate more than 2 fields.
COALESCE([Parent], [AnotherField], 0)
Logical Functions
Demo
Please Follow us on Twitter
Steve Stedman
@SqlEmt
Aaron Buma
@AaronDBuma
Presented by Aaron Buma
User Defined Functions
Scalar
Multiple inputs, one value output
Table Valued
Multiple inputs, row(s) as output
Views
Referencing a query as a table
Scalar Functions - Overview
 What it does:
 Uses one (or many inputs)
 To run one or more queries
 And Return a single value
 What is doesn’t:
 Call non-deterministic functions (ie: GetDate())
 Insert, Update, Deletes to tables or views
 Error handling
 Get included in an execution plan (!Important)
Functions in Views
 Deterministic Functions ex: LEFT()
 You can index the view
 Non-Deterministic Functions ex: GETDATE()
 You cannot index the view, because the data is always
changing
 For UDF’s you need SCHEMABINDING at the function
and view objects
Table Value Function- Overview
 What it does:
 IN: Zero or Many inputs, OUT: a result set
 Single-Statement or Multi-Statement formatting
 What is doesn’t:
 Call non-deterministic functions (ie: GetDate())
 Insert, Update, Deletes to tables or views
 Error handling
 Multi-statement are not included in the execution plan
User Defined Functions
Demo
Any Questions?
 Date and Time Functions
 Logical Functions
 User Defined Functions
Tune in next week
 Thursday 3/26 at 9:00am pacific time
 Back to Basics – JOINs
INNER, LEFT OUTER, RIGHT OUTER, SEMI JOIN,
ANTI SEMI JOIN, LEFT OUTER with exclusion,
RIGHT OUTER with exclusion, FULL OUTER, CROSS
JOIN, FULL OUTER JOIN with exclusion, LATERAL
JOINS, CROSS APPLY, combinations.
For More Information
 Visit http://EmergencyReporting.com to find out more
about Emergency Reporting.
 Aaron on the web
 http://AaronBuma.com
 Twitter: @AaronDBuma
 Steve on the web
 http://SteveStedman.com
 twitter: @SqlEmt

More Related Content

Similar to TSQL Functions (SQL Server)

Data ware dimension design
Data ware   dimension designData ware   dimension design
Data ware dimension designSayed Ahmed
 
Top5 functions sql2012
Top5 functions sql2012Top5 functions sql2012
Top5 functions sql2012Manas Dash
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICAemtrajano
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Fulvio Corno
 
Top 10 excel analytic tests to minimize fraud and process risks
Top 10 excel analytic tests to minimize fraud and process risksTop 10 excel analytic tests to minimize fraud and process risks
Top 10 excel analytic tests to minimize fraud and process risksJim Kaplan CIA CFE
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questionsSunil0108
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questionsDr P Deepak
 
Steve mo's formulas and life hacks frankfurt de 2020-05-07
Steve mo's formulas and life hacks   frankfurt de 2020-05-07Steve mo's formulas and life hacks   frankfurt de 2020-05-07
Steve mo's formulas and life hacks frankfurt de 2020-05-07Alan Thomas Payne
 
Steve mo's formulas and life hacks wellington nz 2020-05-05
Steve mo's formulas and life hacks   wellington nz 2020-05-05Steve mo's formulas and life hacks   wellington nz 2020-05-05
Steve mo's formulas and life hacks wellington nz 2020-05-05Anna Loughnan Colquhoun
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Achmad Solichin
 
1 CMIS 102 Hands-On Lab Week 8 Overview Th.docx
1  CMIS 102 Hands-On Lab  Week 8 Overview Th.docx1  CMIS 102 Hands-On Lab  Week 8 Overview Th.docx
1 CMIS 102 Hands-On Lab Week 8 Overview Th.docxhoney725342
 
Trainer evaluation project
Trainer evaluation projectTrainer evaluation project
Trainer evaluation projectfgaragozlo
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
 
Cmis 102 hands on/tutorialoutlet
Cmis 102 hands on/tutorialoutletCmis 102 hands on/tutorialoutlet
Cmis 102 hands on/tutorialoutletPoppinss
 

Similar to TSQL Functions (SQL Server) (20)

Data ware dimension design
Data ware   dimension designData ware   dimension design
Data ware dimension design
 
LCC Asia Pacific_financialmodelling_excelshortcuts1
LCC Asia Pacific_financialmodelling_excelshortcuts1LCC Asia Pacific_financialmodelling_excelshortcuts1
LCC Asia Pacific_financialmodelling_excelshortcuts1
 
Top5 functions sql2012
Top5 functions sql2012Top5 functions sql2012
Top5 functions sql2012
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICA
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
 
Top 10 excel analytic tests to minimize fraud and process risks
Top 10 excel analytic tests to minimize fraud and process risksTop 10 excel analytic tests to minimize fraud and process risks
Top 10 excel analytic tests to minimize fraud and process risks
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Getting power bi
Getting power biGetting power bi
Getting power bi
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questions
 
SQL Server Stored procedures
SQL Server Stored proceduresSQL Server Stored procedures
SQL Server Stored procedures
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questions
 
Steve mo's formulas and life hacks frankfurt de 2020-05-07
Steve mo's formulas and life hacks   frankfurt de 2020-05-07Steve mo's formulas and life hacks   frankfurt de 2020-05-07
Steve mo's formulas and life hacks frankfurt de 2020-05-07
 
Steve mo's formulas and life hacks wellington nz 2020-05-05
Steve mo's formulas and life hacks   wellington nz 2020-05-05Steve mo's formulas and life hacks   wellington nz 2020-05-05
Steve mo's formulas and life hacks wellington nz 2020-05-05
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
 
1 CMIS 102 Hands-On Lab Week 8 Overview Th.docx
1  CMIS 102 Hands-On Lab  Week 8 Overview Th.docx1  CMIS 102 Hands-On Lab  Week 8 Overview Th.docx
1 CMIS 102 Hands-On Lab Week 8 Overview Th.docx
 
Trainer evaluation project
Trainer evaluation projectTrainer evaluation project
Trainer evaluation project
 
Programming
ProgrammingProgramming
Programming
 
Les03
Les03Les03
Les03
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
Cmis 102 hands on/tutorialoutlet
Cmis 102 hands on/tutorialoutletCmis 102 hands on/tutorialoutlet
Cmis 102 hands on/tutorialoutlet
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

TSQL Functions (SQL Server)

  • 1. Presented by Steve Stedman and Aaron Buma
  • 2. Welcome  Welcome to all those joining us remotely.  For any questions via Google On Air Broadcasts, we will address most of these at the end of the training.  Training provided by Emergency Reporting  http://EmergencyReporting.com  Slides and sample code are available at:  http://SteveStedman.com
  • 3. Welcome Viewers From  Bellingham, WA  Salt Lake City, UT  Glacier, WA  St Louis, MO  Gainesville, FL  Honolulu, HI  Portugal  Chennai, India  Belarus  Bucharest
  • 4. Live Broadcast  Using Google On Air Broadcasts  There is about a 40 to 50 second delay from live to what you see.  We are still learning how to properly use Google On Air Broadcasts. Please be patient.  Session will be available on my YouTube Channel about an hour after the presentation ends.  http://SteveStedman.com/YouTube
  • 5. Questions  We will have time for questions at the end of the session.  Q&A available via Google On Air Hangout panel. Click the 3x3 grid icon near the top right, then select Q&A to see what people are asking, or to ask your own question.  When you ask a question, it shows up for us about 40 to 50 seconds delayed.
  • 6. Agenda  Date and Time Functions  Logical Functions  User Defined Functions
  • 9. GETDATE  Returns the current database system timestamp as a datetime value without the database time zone offset. SELECT GETDATE();
  • 10. DATEPART()  Returns an integer that represents the specified datepart of the specified date. SELECT DATEPART(year, GETDATE());  Date can be time, date, smalldatetime, datetime, datetime2, or datetimeoffset.
  • 11. DATEADD()  Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date. SELECT DATEADD(month, 1, GETDATE());
  • 12. DATEDIFF()  Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate. SELECT DATEDIFF(year, '1/1/2015', GETDATE()); SELECT DATEDIFF(quarter, '1/1/2015', GETDATE()); SELECT DATEDIFF(month, '1/1/2015', GETDATE());
  • 13. DATEFROMPARTS (2012) DATEFROMPARTS ( year, month, day )  Arguments  Year Integer expression specifying a year.  Month Integer expression specifying a month, from 1 to 12.  Day Integer expression specifying a day.  Always Year – Month – Day order independent of language or location
  • 14. TIMEFROMPARTS (2012) TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )  Arguments  Hour Integer expression specifying hours.  Minute Integer expression specifying minutes.  Seconds Integer expression specifying seconds.  Fractions Integer expression specifying fractions.  Precision Integer literal specifying the precision of the time value to be returned.
  • 15. DATETIMEFROMPARTS (2012) DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )  Arguments  Year Integer expression specifying a year.  Month Integer expression specifying a month.  Day Integer expression specifying a day.  Hour Integer expression specifying hours.  Minute Integer expression specifying minutes.  Seconds Integer expression specifying seconds.  Milliseconds Integer expression specifying milliseconds.
  • 16. DATETIME2FROMPARTS (2012) DATETIME2FROMPARTS (year, month, day, hour, minute, seconds, fractions, precision)  Arguments  Year Integer expression specifying a year.  Month Integer expression specifying a month.  Day Integer expression specifying a day.  Hour Integer expression specifying hours.  Minute Integer expression specifying minutes.  Seconds Integer expression specifying seconds.  Fractions Integer expression specifying fractions.  Precision Integer literal specifying the precision of the datetime2 value to be returned.
  • 18. DATETIMEOFFSETFROMPARTS (2012)  DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute, seconds, fractions, hour_offset, minute_offset, precision )  hour_offset - Integer expression specifying the hour portion of the time zone offset.  minute_offset - Integer expression specifying the minute portion of the time zone offset.  Precision - Integer literal specifying the precision of the value to be returned.  Precision can be a value of 0 to 7 which specifies the precision of the fractional part of the seconds.
  • 19. EOMONTH (2012) EOMONTH ( start_date [, month_to_add ] )  Returns the last day of the month that contains the specified date, with an optional offset.  Arguments  start_date Date expression specifying the date for which to return the last day of the month.  month_to_add Optional integer expression specifying the number of months to add to start_date.
  • 20. Date and Time Functions Demo
  • 21. Please Connect on LinkedIn Steve Stedman http://linkedin.com/in/stevestedman Aaron Buma https://www.linkedin.com/in/aaronbuma
  • 24. CASE  Evaluates a list of conditions and returns one of multiple possible result expressions. CASE WHEN Revenue > AverageRevenue THEN 'Better Than Average' ELSE 'Not Better' END AS Ranking
  • 25. CASE with multiple WHEN SELECT CASE @corners WHEN 1 THEN 'point' WHEN 2 THEN 'line' WHEN 3 THEN 'triangle' WHEN 4 THEN 'square' WHEN 5 THEN 'pentagon' WHEN 6 THEN 'hexagon' WHEN 7 THEN 'heptagon' WHEN 8 THEN 'octagon' ELSE NULL END;
  • 26. IIF (2012)  Returns one of two values, depending on whether the Boolean expression evaluates to true or false in SQL Server.  This is similar to Excel or VB versions of IIF. IIF(Revenue > AverageRevenue, 'Better Than Average', 'Not Better' ) AS Ranking  What does IIF stand for? Immediate IF? Inline IF?
  • 27. IIF Details  Performance very similar between IIF and CASE  IIF simplifies the code over using a CASE statement  Can be nested up to 10 levels  The true value and false value cannot both be NULL.
  • 28. CHOOSE (2012)  Function that returns the item at a specific index.  CHOOSE(index, val_1, val_2, val_3, ...)  If the index is greater than the number of values or less than 1 it returns NULL  Easier than CASE in some examples
  • 30. COALESCE  Similar to CASE, or CHOOSE, but returns the first NON NULL value.  Similar to ISNULL when using 2 parameters COALESCE([Parent], 0)  Will accommodate more than 2 fields. COALESCE([Parent], [AnotherField], 0)
  • 32. Please Follow us on Twitter Steve Stedman @SqlEmt Aaron Buma @AaronDBuma
  • 34. User Defined Functions Scalar Multiple inputs, one value output Table Valued Multiple inputs, row(s) as output Views Referencing a query as a table
  • 35. Scalar Functions - Overview  What it does:  Uses one (or many inputs)  To run one or more queries  And Return a single value  What is doesn’t:  Call non-deterministic functions (ie: GetDate())  Insert, Update, Deletes to tables or views  Error handling  Get included in an execution plan (!Important)
  • 36. Functions in Views  Deterministic Functions ex: LEFT()  You can index the view  Non-Deterministic Functions ex: GETDATE()  You cannot index the view, because the data is always changing  For UDF’s you need SCHEMABINDING at the function and view objects
  • 37. Table Value Function- Overview  What it does:  IN: Zero or Many inputs, OUT: a result set  Single-Statement or Multi-Statement formatting  What is doesn’t:  Call non-deterministic functions (ie: GetDate())  Insert, Update, Deletes to tables or views  Error handling  Multi-statement are not included in the execution plan
  • 39. Any Questions?  Date and Time Functions  Logical Functions  User Defined Functions
  • 40. Tune in next week  Thursday 3/26 at 9:00am pacific time  Back to Basics – JOINs INNER, LEFT OUTER, RIGHT OUTER, SEMI JOIN, ANTI SEMI JOIN, LEFT OUTER with exclusion, RIGHT OUTER with exclusion, FULL OUTER, CROSS JOIN, FULL OUTER JOIN with exclusion, LATERAL JOINS, CROSS APPLY, combinations.
  • 41. For More Information  Visit http://EmergencyReporting.com to find out more about Emergency Reporting.  Aaron on the web  http://AaronBuma.com  Twitter: @AaronDBuma  Steve on the web  http://SteveStedman.com  twitter: @SqlEmt