Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

SQL Server Built-In Functions

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

SQL Server Built-In Functions

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

SQL Server Built-in

Functions
SQL Server ASCII() Functions: Returns ASCII Code
In SQL Server, the ASCII() function returns the ASCII code value of the leftmost character of the specified
number or character value.

ASCII stands for American Standard Code for Information Interchange. It serves as the character encoding
standard for electronic communication.

ASCII(string)

Example
SELECT ASCII('A') A, ASCII('ABC') ABC
The following example demonstrates the ASCII() function and returns an ASCII code for a character and
string. For string value, it returns the ASCII code of the first character.

You can pass the column of a database table as a parameter. In the following example, the ASCII()
function returns the ASCII code for FirstName and LastName column values.

Example: ASCII()
SELECT FirstName as EmpName, ASCII(FirstName) as ASCIIFirstValue,
SQL Server CHAR() Function: Returns ASCII of
Integer
The CHAR() function returns the ASCII code of the specified integer from 0 to 255. You can also specify
an expression that returns an integer value.

Syntax
CHAR(integer_expression)

The CHAR() function can be used with the SELECT statement to get the ASCII code of the specified
value.

Example: CHAR()
select char(65) as char65
SQL Server CHARINDEX() Functions: Returns Starting Index of Substring

The CHARINDEX() function returns the starting position of the substring or character in another string.
It returns 0 if substring is not found.

CHARINDEX(substring, string [, start_location])

Example 1:
The following example searches 'e' in the string 'Hello World' and returns its index position.

SELECT CHARINDEX('e', 'Hello world')


SQL Server CONCAT() Function: Concatenates Strings

The CONCAT() function joins two or more string expressions in an end-to-end manner and returns a single
string.

CONCAT(string1, string2 [, stringN])

The following example concatenates two strings.

Example: CONCAT()
SELECT CONCAT('Good ', 'Morning!') as Greetings;

The CONCAT() function can be used to database table's columns. The following join the FirstName column, a
string with white space, and the LastName column of the Employee table.

Example: CONCAT()
SELECT CONCAT(emp.FirstName,' ' , emp.LastName) as EmployeeName;
FROM Employee emp;
SQL Server LEFT() Function: Returns Substring from Left

In SQL Server, the LEFT() function returns the specified number of characters from the left side of the
specified string.

LEFT(character_expression, number_of_characters)

The following example uses the LEFT() function to extract five characters from the left of an input string.

Example: LEFT()
SELECT LEFT('Hello world', 5);

The following uses the LEFT() function with the column of the database table.

Example: LEFT()
SELECT LEFT(FirstName, 3) AS Tag FROM Employee;
SQL Server LEN() Function: Count Characters in String
In SQL Server, the LEN() function returns the total count of the characters of the specified
input string, excluding the trailing spaces.

LEN (string_expression)

The following example returns the number of characters using the LEN() function.

SELECT LEN ('HELLO WORLD') AS Result

In the following example, the LEN() function is used on a string with trailing spaces. LEN
ignores the trailing spaces as shown in the result.

SELECT LEN('HELLO WORLD ') AS WithTrailingSpaces

In the following example, the LEN function is used with the column, FirstName of Employee table.

Example: LEN() Copy


SQL Server LOWER() Function: Convert String to Lower
Case
In SQL Server, the LOWER() function converts the specified string into lower case.

LOWER(character_expression)

SELECT LOWER('Hello World') AS Lowercase, LOWER('ABCDEF') AS LowerCaseAlphabets


In the following example, strings ‘Hello World’ and ‘ABCDEF’ are converted to lower case.

SELECT LOWER(FirstName) AS FirstName, LOWER(LastName) AS LastName FROM Employee


In the following example, FirstName and LastName columns from the Employee table are converted to
lowercase.
SQL Server LTRIM() Function: Removes Leading Spaces
In SQL Server, the LTRIM() function removes the leading space from the beginning of the specified string
and returns it.

LTRIM(character_expression)

SELECT ' Remove leading spaces' AS InputString,

LTRIM(' Remove leading spaces') AS Result


In the following example, the leading spaces in a string are trimmed using the LTRIM() function.

SELECT AddressID, LTRIM(Address) AS Address FROM Address


Use the LTRIM() function to trim the leading spaces from the Address column, as shown below.
SQL Server RTRIM() Function: Removes Trailing Spaces
In SQL Server, the RTRIM() function removes all the trailing spaces from right side in the specified string
and returns a new string.

RTRIM(input_string)

In the following example, the RTRIM() is used to trim the trailing spaces in a string, as shown below.

SELECT RTRIM('Have a nice day! ')


Use the LTRIM() and RTRIM() functions together to truncate leading and trailing blanks from the string,
as shown below.

SELECT LTRIM(RTRIM(' Have a nice day! ')) AS Greetings;


SQL Server SUBSTRING() Function
In SQL Server, the SUBSTRING() function returns a part of a given string. The given string can be of
character, binary, text, or image type.

SUBSTRING(expression, start, length)

In the following example a part of the given sentence 'Hello World' is returned.

SELECT SUBSTRING('Hello World', 7, 5) AS Result;

In the following example, the SUBSTRING() function is used on the FirstName column of the Employee table
to return a substring with 4 characters.

SELECT SUBSTRING(FirstName, 1,4) AS NickName FROM Employee;


SQL Server NCHAR() Function
In SQL Server, NCHAR() function returns the Unicode character with the specified integer code, as defined
by the Unicode standard.

NCHAR(integer_expression)

In the following example, pass 123 to the NCHAR()function.

SELECT NCHAR (123) AS Result;

The NCHAR() function will return NULL if you pass a positive integer greater than 65535, as shown below.

SELECT NCHAR(665578) AS Result;


SQL Server PATINDEX() Function

In SQL Server, PATINDEX() searches for the first occurrence of a pattern in a given expression
and returns its starting position. It returns zero if the pattern is not found.

PATINDEX(pattern, input_string)

The following example finds the 'llo' in the input string 'Hello! Have a nice day.'. The pattern
should be surrounded by %.

SELECT PATINDEX ('%llo%', 'Hello! Have a nice day.') AS PatternPosition

In the following example, we find the pattern 'abc.com' in the Email column of the
Employee table. All rows having this pattern in their Email column, return the starting
position of the pattern and rows not having this pattern in their Email returns zero.

SELECT Email, PATINDEX('%abc.com%', EMail) AS PatternPosition FROM Employee


SQL Server REPLACE() Function

In SQL Server, the REPLACE() function replaces all occurrences of the given string with the
specified substring.

REPLACE(string_expression, search_pattern, stringToReplace)

The following example demonstrates the REPLACE() function

SELECT REPLACE('abcdefghabcdefgh','abcd','****') AS Result1,


REPLACE('abcd efg h abc de fgh','abcd','****') AS Result2;

In the following example, the word 'nice is replaced with the word 'good' in the input string
'Hello! Have a nice day.'

SELECT REPLACE('Hello! Have a nice day.', 'nice', 'good') AS Greetings;


SQL Server RIGHT() Function

In SQL Server, the RIGHT() function returns the specified number of characters from the
right side of the specified string.

RIGHT(string_expression, number_of_charaters)

In this following example, the RIGHT() function returns the rightmost three characters of the
specified string.

SQL Query: SELECT RIGHT('Have a nice day', 3) AS Result

In the following example, the rightmost four characters of the FirstName column are
returned.

SELECT FirstName, RIGHT(FirstName,4) AS Result FROM Employee;


SQL Server SPACE() Function

In SQL Server, the SPACE() function returns a string with the specified number of spaces
limited to 8000 spaces.

SPACE(number_of_spaces)

In this simple example, a string of 50 spaces is returned.

SELECT SPACE(50) AS Result;

The SPACE() function can be used for adding fewer spaces for the easy readability of a
query.

SELECT 'Move' + SPACE(3) + 'away!' AS Result;


SQL Server STR() Function

In SQL Server, STR() function returns the numeric data as string.

STR(numeric_expression [,length [ ,decimal]])

In the following example, STR(123.76, 6, 2) returns "123.76". 6 is the total length of the
result including decimal point, 2 is decimal points in the result.

SELECT STR(123.76, 6, 2) AS Result

In the following example, STR(123.76, 6, 1) returns "123.8" because the decimal parameter
is 1, so it will rounded up to largest value.

SELECT STR(123.76, 6, 1) AS Result


SQL Server STUFF() Function

In SQL Server, the STUFF() function inserts a string into another string. It deletes a specified
number of characters from the first string starting at the specified position and inserts the
given second string from that position.

STUFF(string_expression, start, length, replacementString)

In the following simple example, a given string 'abcdefgh' is replaced from the third
character to a length of six characters, by 'xxxx'.

SELECT STUFF('abcdefgh',3,6,'xxxx') AS Result;

In the following example, 'nice' is deleted and replaced with the word 'good'.

SELECT STUFF('Have a nice day!',8,4,'good') AS Result


SQL Server CURRENT_TIMESTAMP() Function

In SQL Server, the CURRENT_TIMESTAMP() function returns the current system timestamp of the
server on which the SQL Server database instance is installed. It is returned as a datetime
value without the time zone offset.

CURRENT_TIMESTAMP()

In the following example, the CURRENT_TIMESTAMP() is used to get the current date and time
value of the server hosting the SQL Server database instance.

SELECT CURRENT_TIMESTAMP AS CurrentServerDateTime;

In the following example, the CURRENT_TIMESTAMP is used as a default value of a column.

CREATE TABLE tblEmployeeLogin ( EmpLogin DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP


)
SQL Server DATEADD() Function

In SQL Server, the DATEADD() function adds a number to a datepart and returns the modified
datetime value.

DATEADD(datepart, number, date)

The following example adds 1 day to the specified date '12/31/2021' (31st December
2021).

SELECT DATEADD(day,1,'12/31/2021') AS Result

In this example, for the month datepart, 2 is added to date '12/31/2021'. As you can see in
the result, two months is added to the input date and the DATEADD() function returns 28th
February 2022, which is the last day of the returned date.

SELECT DATEADD(month, 2, '12/31/2021') AS Result


SQL Server DATEDIFF() Function
In SQL Server, the DATEDIFF() function returns the difference between the specified start date and end
date in integer. It can be difference between days, months, weeks, hours, seconds based on the
passed datepart parameter.

DATEDIFF(datepart, startdate, enddate)

In the below example, the startdate is bigger than the enddate, and so the DATEDIFF() function returns
a negative value.

SELECT DATEDIFF(day, '12/23/22', '01/11/2022') AS ReturnDate

The DATEDIFF() function can also return the difference between the specified time values when
datepart parameter is HH, MI, and SS.

select datediff(HH,'3:22:59','4:23:50') as HoursDiff,


datediff(MI,'3:20:59','4:23:50') as MinsDiff,
datediff(SS,'4:22:59', '4:23:50') as SecDiff;
SQL Server DATENAME() Function

In SQL Server, the DATENAME() function returns a string that represents the specified datepart
of a given date.

DATENAME(datepart, date)

In the followin example, month part of current date is returned

SELECT DATENAME(mm,GETDATE())AS ThisMonth

The following uses the DATENAME() function with the DateTime type column of a table that
returns a year as a string.

SELECT EmployeeId, DATENAME(yy, HireDate) AS HireYear FROM Employee


SQL Server DATEPART() Function

In SQL Server, the DATEPART() function returns an integer representing the specific part of the
given date e.g. day, month, year, hour, seconds, etc.

DATEPART (datepart, date)

In the following example, the DATEPART() function returns the month of the given date as an
integer.

SELECT GETDATE() AS Today,


DATEPART(mm, GETDATE()) AS CurrentMonth

In the following example, the DATEPART function is used with the HireDate column of the Employee
table and returns the Quarter and Year of hiring employees.

SELECT EmployeeID, DATEPART(q, HireDate) AS QuarterHired,


SQL Server DAY() Function

In SQL Server, the DAY() function returns the DAY part of the given date as an integer.

DAY(date)

In the following example, the DAY() function returns a day string of the specified datetime
value.

SELECT DAY('02/17/2022 10:30:29') AS DayOfMonth

In the following example, the DAY() function is used to get the day part of the HireDate
column of the Employee table.

SELECT EmployeeID, FirstName, HireDate, DAY(HireDate) as Hireday FROM Employee


SQL Server GETDATE() Function

In SQL Server, the GETDATE() function returns the current date as a datetime value without the
database time zone offset. This value is derived from the operating system of the computer on
which the SQL Server is running.

GETDATE()

In the following example, the GETDATE() function is used in the SELECT statement to get the
current timestamp of the computer running SQL Server.

SELECT GETDATE() AS CurrentDateTime

Use the CONVERT() function with GETDATE() to get only the date or time portion of the current date
value.

SELECT CONVERT(DATE, GETDATE()) AS CurrentDate,


CONVERT(DATE, GETDATE()) AS CurrentTime;
SQL Server GETUTCDATE() Function

In SQL Server, the GETUTCDATE() function returns the current system UTC(Coordinated Universal
Time) as a datetime. This does not include the time zone offset. This value is derived from the
operating system of the computer hosting the SQL Server instance.

GETUTCDATE()

In the following example, the GETUTCDATE() function returns the current UTC datetime of the
computer running SQL Server instance.

SELECT GETUTCDATE() AS CurrentUTCDateTime

Use the CONVERT() function with GETUTCDATE() to get the current date or time portion.

SELECT CONVERT(date, GETUTCDATE()) AS CurrentUTCDate,

CONVERT(time, GETUTCDATE()) AS CurrentUTCTime;


SQL Server MONTH() Function

In SQL Server, the MONTH() function returns the month as an integer from the specified date.
It returns 1 for January, 2 for February, and so on.

MONTH(date)

In the following example, the MONTH() function returns a month as an integer from the
specified date string literal in 'MM/dd/yyyy' format.

SELECT MONTH ('11/23/2022') AS Month

The MONTH() function returns 1 if you pass a time string value.

SELECT MONTH('10:22:15') AS Result


SQL Server YEAR() Function

In SQL Server, the YEAR() function returns the year of the specified date as an integer.

YEAR(date)

In the following example, date as a string literal is passed to the YEAR() function

SELECT YEAR ('11/23/2022') AS Year

In the following example, the specified date parameter has just the time.

SELECT YEAR ('10:22:15') AS Result


SQL Server ISDATE() Function

In SQL Server, the ISDATE() function returns 1 if the input expression is a valid datetime
value, else it returns 0.

ISDATE(input_expression)

In the following example, the ISDATE() validates whether the specified date string is a valid
date or not. It returns 1 if valid date otherwise returns 0.

SELECT ISDATE ('2022-10-20') AS IsValidDate

In the following example, the ISDATE() function validates whether the specified string is a
valid datetime value or not.

SELECT ISDATE ('2022-10-20 10:10:20') AS IsValidDate

You might also like