sqlsql

SQL Server Functions

1. Introduction

SQL Server is a relational database management system (RDBMS) solution created by Microsoft Corporation. Focus in this treatise will be on SQL Server functions, href=”https://docs.microsoft.com/en-us/sql/t-sql/functions/functions?view=sql-server-ver15. Some functions discussed here can also be found in other RDBMS.

2. Background

SQL functions, in general, typically will allow for parameters to be used to call them. This will result in a value that can be displayed or subsequently used as input to yet another function. This is known as the nesting of functions. Functions will activate instructions that can perform the calculation or manipulate the parameters, which can be any expression. An expression can be a value or a name of a column of a specified table.

3.1 SQL Server String Functions

NameParametersReturn TypeDescription
ASCII
expressionStringRequired
IntegerReturns integer representation of the first character of the expression.
CHAR
expressionIntegerRequired
CharacterReturns character (ASCII) representation of the expression. The expression must be between 0 and 255.
CHARINDEX
expression to search forStringRequired
expression to be searchedStringRequired
startIndexIntegerOptional
IntegerReturn location of the first occurrence of the first character in expression to search for to be found in expression to be searched. The return value will be between 1 and the length of expression to be searched, or 0 if the character is not found.
CONCAT
expression(s)StringRequired
StringReturn string with n number of expression(s) merged end to end, where n is 1 or greater.
CONCAT_WS
expression(s)StringRequired
StringSame as CONCAT except inserts a separator between expression(s).
DIFFERENCE
expression 1StringRequired
expression 2StringRequired
IntegerReturn integer difference betwen the SOUNDEX() values of expression 1 and expression 2.
FORMAT
valueAnyRequired
formatStringRequired
cultureStringOptional
StringReturn string with value in format specified by format.
LEFT
expressionStringRequired
numberIntegerRequired
StringReturn string with the leftmost number of characters of expression.
LEN
stringStringRequired
IntegerReturn length of string, excluding trailing spaces.
LOWER
expressionStringRequired
StringReturn string with the expression converted to lowercase.
LTRIM
expressionStringRequired
StringReturn string with leading spaces removed from expression.
NCHAR
expressionIntegerRequired
CharacterReturn unicode character of expression.
PATINDEX
patternStringRequired
expressionStringRequired
IntegerReturn integer location of first occurrence of pattern found in expression</strong. Returns 0 if pattern is not found.
QUOTENAME
expressionStringRequired
quote characterCharacterOptional
StringReturn Unicode string expression with delimiter quote character to make valid SQL Identifier.
REPLACE
expressionStringRequired
expression to be replacedStringRequired
replacement expressionStringRequired
StringReturn string with expression to be replaced found in expression replaced by replacement expression.
REPLICATE
expressionStringRequired
numberIntegerRequired
StringReturn string made up expression repeated number times.
REVERSE
expressionStringRequired
StringReturn string from expression where characters are added from the back to the front order.
RIGHT
expressionStringRequired
numberIntegerRequired
StringReturn string with the rightmost number of characters of expression.
RTRIM
expressionStringRequired
StringReturn a string with trailing spaces removed from expression.
SOUNDEX
expressionStringRequired
StringReturn string based on how expression sounds.
SPACE
expressionIntegerRequired
StringReturn string made up of expression number of spaces.
STR
stringFloatRequired
lengthIntegerOptional
decimalIntegerOptional
StringReturn string with expression expressed as string. Result is right-justified dependent on length(default: 10) and decimal(0-16).
STRING_AGG [WHERE clause permitted]
expressionStringRequired
separatorStringRequired
StringReturn string with expression end-to-end with separator inserted except for last occurrence. Where clause is permitted to allow for criteria to be specified for expression to be included.
STRING_ESCAPE
expressionStringRequired
typeStringRequired
StringReturn string where expression has characters escaped according to type. Currently, type supports ‘json’.
STUFF
expressionStringRequired
start indexIntegerRequired
lengthIntegerRequired
replacement expressionStringRequired
StringReturn string where length long part of expression is removed and replaced with replacement expression.
SUBSTRING
expressionStringRequired
indexIntegerRequired
lengthIntegerRequired
StringReturn string of part of expression starting at location index for length characters. Index of 1 indicates the start from first character of the string. length cannot exceed the length of expression.
TRANSLATE
expression to be manipulatedStringRequired
expression with characters to be replacedStringRequired
expression with characters to be replaced withStringRequired
StringReturn string with occurrences of expression with characters to be replaced found in expression to be manipulated replaced by expression with characters to be replaced with.
TRIM
expressionStringRequired
StringReturn a string with expression, having leading and trailing spaces removed.
UNICODE
expressionStringRequired
IntegerReturn unicode of first character of expression.
UPPER
expressionStringRequired
StringReturn a string with expression converted to uppercase
String Functions

3.2 SQL Server Math/Numeric Functions

NameParametersReturn TypeDescription
ABS
expressionFloatRequired
FloatReturn absolute(positive) value of expression.
ACOS
expressionFloatRequired
FloatReturn angle, in radians whose cosine is equal to expression. expression must be between -1.0 and 1.0.
ASIN
expressionFloatRequired
FloatReturn angle, in radians whose sine is equal to expression. expression must be between -1.0 and 1.0
ATAN
expressionFloatRequired
FloatReturn angle, in radians whose tangent is equal to expression.
ATN2
yFloatRequired
xNumberRequired
FloatReturn angle, in radians whose tangent has a x-coordinate of x and a y-coordinate of y.
CEILING
expressionFloatRequired
IntegerReturn smallest integer number greater than or equal to expression.
COS
expressionFloatRequired
FloatReturn cosine of the expression(in radians)
COT
expressionFloatRequired
FloatReturn cotangent of the expression(in radians).
DEGREES
expressionFloatRequired
FloatReturn degrees of the expression(in radians).
EXP
expressionFloatRequired
FloatReturn e (~2.71) raised to expression power.
FLOOR
expressionFloatRequired
IntegerReturn greatest integer less than or equal to expression.
LOG
expressionFloatRequired
FloatReturn natural logarithm (base e) of expression.
LOG10
expressionFloatRequired
FloatReturn logarithm (base 10) of expression.
PI
No arguments
FloatReturn value of PI (~3.14).
POWER
expressionFloatRequired
exponentFloatRequired
FloatReturn float of expression raised to the power of exponent.
RADIANS
expressionFloatRequired
FloatReturn radian equivalent of expression(in degrees)
RAND
seedIntegerOptional
FloatReturn randomly generated number between 0 and 1, exclusive.
ROUND
expressionNumberRequired
lengthIntegerRequired
functionNumberOptional
NumberReturn rounded off expression as specified by length.
SIGN
expressionFloatRequired
NumberReturn -1 if expression is negative, +1 if expression is positive, otherwise 0.
SIN
expressionFloatRequired
FloatReturn sine of expression (in radians).
SQRT
expressionFloatRequired
FloatReturn square root of expression.
SQUARE
expressionFloatRequired
FloatReturn square of expression or expression times expression.
TAN
expressionFloatRequired
FloatReturn tangent of expression (in radians).
Math/Numeric Functions

3.3 SQL Server Date Functions

NameParametersReturn TypeDescription
CURRENT_TIMESTAMP
No arguments
DateTimeReturn current datetime
DATEADD
datepart (see below)Required
Date PartEquivalents
yearyy, yyyy
quarterq, qq
monthm, mm
dayofyeardy, y
dayd, dd
weekwk,ww
weekdaydw,w
hourhh
minutemi, n
seconds, ss
millisecondms
microsecondmcs
nanosecondns
expressionIntegerRequired
dateDate,DateTime, DateTimeOffset, DateTime2, SmallDateTime or TimeRequired
DateTimeReturn datetime with expression added to date. What is added is determined by datepart
DATEDIFF
datepart (see below)Required
Date PartEquivalents
yearyy, yyyy
quarterq, qq
monthm, mm
dayofyeardy, y
dayd, dd
weekwk,ww
weekdaydw,w
hourhh
minutemi, n
seconds, ss
millisecondms
microsecondmcs
nanosecondns
date 1DateTimeRequired
date 2DateTimeRequired
IntegerReturn integer difference between date 1 and date 2. datepart determines what time units to get difference of.
DATEDIFF_BIG
datepart (see below)Required
Date PartEquivalents
yearyy, yyyy
quarterq, qq
monthm, mm
dayofyeardy, y
dayd, dd
weekwk,ww
weekdaydw,w
hourhh
minutemi, n
seconds, ss
millisecondms
microsecondmcs
nanosecondns
date 1DateTimeRequired
date 2DateTimeRequired
Big IntegerAllows for larger numbers than DATEDIFF
DATEFROMPARTS
yearNumberRequired
monthNumberRequired
dayNumberRequired
DateTimeReturn dateTime with year-month-day
DATENAME
datepart (see below)Required
Date PartEquivalents
yearyy, yyyy
quarterq, qq
monthm, mm
dayofyeardy, y
dayd, dd
weekwk,ww
weekdaydw,w
hourhh
minutemi, n
seconds, ss
millisecondms
microsecondmcs
nanosecondns
dateDateTimeRequired
StringReturn string representation part of date as determined by datepart.
DATEPART
datepart (see below)Required
Date PartEquivalents
yearyy, yyyy
quarterq, qq
monthm, mm
dayofyeardy, y
dayd, dd
weekwk,ww
weekdaydw,w
hourhh
minutemi, n
seconds, ss
millisecondms
microsecondmcs
nanosecondns
dateDateTimeRequired
IntegerReturn integer part of date as determined by datepart.
DATETIME2FROMPARTS
yearIntegerRequired
monthIntegerRequired
dayIntegerRequired
hourIntegerRequired
minuteIntegerRequired
secondsIntegerRequired
fractionsIntegerRequired
precisionIntegerRequired
DateTimeReturn dateTime with year-month-day hour:minute:seconds.fractions with precision.
DATETIMEFROMPARTS
yearIntegerRequired
monthIntegerRequired
dayIntegerRequired
hourIntegerRequired
minuteIntegerRequired
secondsIntegerRequired
millisecondsIntegerRequired
DateTimeReturn dateTime with year-month-day hour:minute:seconds.milliseconds.
DATETIMEOFFSETFROMPARTS
yearIntegerRequired
monthIntegerRequired
dayIntegerRequired
hourIntegerRequired
minuteIntegerRequired
secondsIntegerRequired
fractionsIntegerRequired
hour offsetIntegerRequired
minute offsetIntegerRequired
precisionIntegerRequired
DateTime OffsetReturn dateTime offset with year-month-day hour:minute:seconds.fractions with precision. hour offset and minute offset represent timezone offset.
DAY
dateDateTimeRequired
IntegerReturn day part of date.
EOMONTH
dateDateTimeRequired
DateTimeReturn datetime of the last day of the month specified by the date.
GETDATE
No arguments
DateTimeReturn current datetime
GETUTCDATE
No arguments
DateTimeReturn current datetime
ISDATE
dateStringRequired
IntegerReturn 1 if date is a valid date, 0 otherwise.
MONTH
dateDateTimeRequired
IntegerReturn month number of date.
SMALLDATETIMEFROMPARTS
yearIntegerRequired
monthIntegerRequired
dayIntegerRequired
hourIntegerRequired
minuteIntegerRequired
Small DateTimeReturn dateTime with year-month-day hour:minute.
SWITCHOFFSET
dt offset expressiondatetime offsetRequired
tz offset expressiontimezone offset expressionRequired
DateTime OffsetReturn datetime offset in different time zone.
SYSDATETIME
No arguments
DateTimeReturn current datetime
SYSDATETIMEOFFSET
No arguments
DateTime OffsetReturn current datetime offset.
SYSUTCDATETIME
No arguments
DateTimeReturn current datetime
TIMEFROMPARTS
hourIntegerRequired
minuteIntegerRequired
secondsIntegerRequired
fractionsIntegerRequired
precisionIntegerRequired
TimeReturn time with hour:minute:seconds.fractions with precision.
TODATETIMEOFFSET
dt expressionDateTimeRequired
tz offset expressiontimezone offset expressionRequired
DateTime OffsetReturn datetime offset in different time zone of dt expression depending on tz offset expression.
YEAR
datetime, date, smalldatetime, datetime, datetime2 or datetimeoffsetRequired
IntegerReturn year of date.
Date Functions

3.4 SQL Server Advanced Functions

A subset of additional functions will be included in the following table:

NameParametersReturn TypeDescription
AVG
expression(s)NumberRequired
NumberReturn average of values (from rows of numeric fields) in group matching a criteria.
COUNT
expression(s)AnyRequired
IntegerReturns count of values (rows) matching a criteria.
MAX
expression(s)AnyRequired
AnyReturns maximum value for group of values (rows of fields) matching a criteria.
MIN
expression(s)AnyRequired
AnyReturns minimum value for group of values (rows of fields) matching a criteria.
SUM
expression(s)NumberRequired
NumberReturn sum of values (from rows of numeric fields) in group matching a criteria.
ISNULL
check expressionAnyRequired
replacement valueAnyRequired
AnyReturn expression is not null, otherise replacement value.
ISNUMERIC
expressionAnyRequired
IntegerReturn 1 if expression is numeric, otherwise 0.
HOST_NAME
No Arguments
StringReturn name of workstation/server.
HOST_ID
No Arguments
StringReturn identification number of workstation/server.
Advanced Functions

4. How are functions used?

  • SQL Functions are used in queries
  • SQL Functions are used in database applications ( stored procedures or stored functions ). Stored procedures/functions are programs that are created and associated with a RDBMS. They are typically executed on the database server and are associated with a specific database. They are also typically migrated onto other servers/environments along with the database.

5. Summary

Software development encourages reuse and modularization. “Why invent the Wheel ?”. Tools, such as functions, have been developed, used often, tweaked, and re-tweaked. They are used to build bigger and more sophisticated tools (applications) to solve a particular problem. Functions are in the toolbox of software developers to build applications.

Frank Yee

Frank holds a Bachelor of Science in Biology from The City University of New York (The City College of New York) and a Bachelor of Arts in Computer Science from The City University of New York (Hunter College). As an undergraduate, he had taken courses where programs were written in Fortran, Basic, Pascal, COBOL, and Assembly Language for the IBM 4341 Mainframe. He has been a software developer for over 30 years having built desktop apps, mobile apps and web apps. He has built software in C/C++, VisualBasic, TCL, Java, PHP, XML/XSLT, Perl, Shell Scripting and Python. Frank was also an educator in The City University of New York (Borough of Manhattan Community College, New York City College of Technology) having taught courses in Pascal, VisualBasic, C++ for over 10 years. Finally, he has recently helped students create programs in Lisp, R, Masm, Haskell, Scheme and Prolog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button