Understanding SQL Server Functions
Functions are crucial components in SQL Server that allow you to perform calculations, manipulate data, and control program flow. They can be broadly categorized into built-in functions provided by SQL Server and user-defined functions (UDFs) that you can create to encapsulate specific logic.
String Functions
These functions are used to manipulate string data types.
CONCAT
Concatenates two or more string values.
LEN
Returns the number of characters in a string.
LOWER
Converts a string to lowercase.
UPPER
Converts a string to uppercase.
SUBSTRING
Extracts a part of a string starting from a specified position.
REPLACE
Replaces all occurrences of a specified substring with another substring.
Numeric Functions
These functions operate on numeric data types.
ABS
Returns the absolute value of a number.
ROUND
Rounds a number to a specified number of decimal places.
CEILING
Returns the smallest integer greater than or equal to a number.
FLOOR
Returns the largest integer less than or equal to a number.
RAND
Returns a random float value between 0 and 1.
Date & Time Functions
These functions are used for working with dates and times.
GETDATE
Returns the current database system date and time.
DATEADD
Adds a specified time interval to a date.
DATEDIFF
Returns the number of date/time parts between two specified dates.
DATENAME
Returns a character string representing the specified datepart of the specified date.
DATEPART
Returns an integer representing the specified datepart of the specified date.
Aggregate Functions
Aggregate functions perform a calculation on a set of values and return a single value. Common examples include COUNT
, SUM
, AVG
, MIN
, and MAX
.
User-Defined Functions (UDFs)
UDFs allow you to create your own functions to perform custom operations. They can improve code reusability and readability.
Scalar UDFs
Scalar UDFs return a single value. They are created using the CREATE FUNCTION
statement.
Usage:
Table-Valued UDFs
Table-valued UDFs return a table. They can be inline or multi-statement.
Usage:
Experiment with these functions to enhance your SQL queries and build more powerful database solutions.