Table of Contents
Objective of this article is to put all mostly used function related in SQL Server 2005. There are several function that we are used regularly in SQL Server 2005. This article is will a common place for all those function with proper example.
But, I need your help. This Table of Contents and Article is editable by all Silver members and above. What I want you to do is replace the entries in the Table of Contents below add as many as function you aware on SQL Server 2005 or above. This will really help beginners to find out all of them under a single article.
I am starting with few function related to DateTime
function. I will update the article regular manner, but I expect a major contribution from you guys. Please don't forget to update the History list with your name and code project profile link.
Thanks in advance for supporting my one small initiative.
Below are the most commonly used DateTime
function in SQL Server.
- GETDATE()
- DATEADD()
- DATEPART()
- DATEDIFF()
- DATENAME()
- DAY()
- MONTH()
- YEAR()
GETDATE()
is very common used method which returns exact date time from the system. It does not accept any parameter. Just call it like simple function.
Example :
Collapse Declare @Date datetime
set @Date = (SELECT GETDATE());
Print @Date
OutPut:
Collapse Aug 15 2009 9:04PM
DATEADD()
DATEADD()
is used to add or subtract datetime. Its return a new datetime based on the added or subtracted interval.
General Syntax
Collapse DATEADD(datepart, number, date)
datepart
is the parameter that specifies on which part of the date to return a new value. Number
parameter is used to increment datepart.
Example :
Collapse Declare @Date datetime
set @Date = (SELECT GETDATE());
print @Date -- Print Current Date
-- Adding 5 days with Current Date
SELECT DATEADD(day, 5,@Date ) AS NewTime
Output :
Collapse Aug 15 2009 9:19PM
NewTime
-----------------------
2009-08-20 21:19:15.170
DATEPART()
is used when we need a part of date or time from a datetime variable. We can use DATEPART
() method only with select command.
Syntax
Collapse DATEPART(datepart, date)
Example :
Collapse -- Get Only Year
SELECT DATEPART(year, GETDATE()) AS 'Year'
-- Get Only Month
SELECT DATEPART(month, GETDATE()) AS 'Month'
-- Get Only hour
SELECT DATEPART(hour, GETDATE()) AS 'Hour
Output :
Collapse Year
-----------
2009
Month
-----------
8
Hour
-----------
21
DATEDIFF()
is very common function to find out the difference between two DateTime
elements.
Syntax
Collapse DATEDIFF(datepart, startdate, enddate)
Example :
Collapse -- Declare Two DateTime Variable
Declare @Date1 datetime
Declare @Date2 datetime
-- Set @Date1 with Current Date
set @Date1 = (SELECT GETDATE());
-- Set @Date2 with 5 days more than @Date1
set @Date2 = (SELECT DATEADD(day, 5,@Date1 ))
-- Get The Date Difference
SELECT DATEDIFF(day, @Date1, @Date2) AS DifferenceOfDay
Output :
Collapse DifferenceOfDay
---------------
5
DATENAME()
is very common and most useful function to find out the date name from the datetime value.
Example
Collapse -- Get Today
SELECT DATENAME(dw, getdate()) AS 'Today Is'
-- Get Mont name
SELECT DATENAME(month, getdate()) AS 'Month'
Output :
Collapse Today Is
------------------------------
Saturday
Month
------------------------------
August
DAY()
is used to get the day from any date time object.
Example:
Collapse SELECT DAY(getdate()) AS 'DAY'
Output :
Collapse DAY
-----------
15
Collapse SELECT MONTH(getdate()) AS 'Month'
Output :
Collapse Month
-----------
8
Collapse SELECT YEAR(getdate()) AS 'Year'
Output :
Collapse Year
-----------
2009
Some of the String Functions comes very handy at times. Let us discuss them one by one.
ASCII()
Returns the ASCII code value of the leftmost character of a character expression.
Syntax
Collapse ASCII ( character_expression )
Arguments: character_expression : Is an expression of the type char or varchar.
- Return Types: Int
Example:
Collapse SELECT ASCII('A')
SET TEXTSIZE 0
SET NOCOUNT ON
DECLARE @position int, @string char(15)
SET @position = 1
SET @string = 'The codeProject'
WHILE @position <= DATALENGTH(@string)
BEGIN
SELECT ASCII(SUBSTRING(@string, @position, 1)),
CHAR(ASCII(SUBSTRING(@string, @position, 1)))
SET @position = @position + 1
END
SET NOCOUNT OFF
Output:
Collapse
65
84 T
104 h
101 e
and so on.....
CHAR()
Converts an int ASCII code to a character.
Syntax
Collapse CHAR ( integer_expression )
Arguments: integer_expression: Is an integer from 0 through 255. NULL is returned if the integer expression is not in this range.
Return Types: character
Example:
Collapse SET TEXTSIZE 0
SET NOCOUNT ON
DECLARE @intCounter int
SET @intCounter = 0
WHILE (@intCounter<= 255)
BEGIN
SELECT 'CHAR - ' + CHAR(@intCounter) + '. ASCII - ' + CONVERT(VARCHAR,@intCounter)
SET @intCounter = @intCounter + 1
END
SET NOCOUNT OFF
Output:
Collapse CHAR - !. ASCII - 33
CHAR - ". ASCII - 34
------------------------------------------------
CHAR - #. ASCII - 35
------------------------------------------------
CHAR - $. ASCII - 36
------------------------------------------------
CHAR - %. ASCII - 37
------------------------------------------------
CHAR - &. ASCII - 38
------------------------------------------------
CHAR - '. ASCII - 39
------------------------------------------------
CHAR - (. ASCII - 40
------------------------------------------------
and so on.....
NCHAR()
Return a unicode character representing a number passed as a parameter.
Syntax
Collapse NCHAR ( integer_expression )
Return Types: character
Example :
Collapse SELECT NCHAR(97)
OutPut
Collapse This will return the leter "a"
DIFFERENCE()
Returns an integer value that indicates the difference between the SOUNDEX values of two character expressions.
Syntax
Collapse DIFFERENCE ( character_expression , character_expression )
Arguments:character_expression: Is an expression of type char or varchar. character_expression can also be of type text; however, only the first 8,000 bytes are significant.
Return Types: Int
Example :
Collapse USE AdventureWorks;
GO
SELECT SOUNDEX('Green'), SOUNDEX('Greene'), DIFFERENCE('Green','Greene');
GO
SELECT SOUNDEX('Blotchet-Halls'), SOUNDEX('Greene'), DIFFERENCE('Blotchet-Halls', 'Greene');
GO
Output:
Collapse
G650 G650 4
(1 row(s) affected)
B432 G650 0
(1 row(s) affected)
LEFT()
Returns the left most characters of a string.
Syntax
Collapse LEFT(string, length)
string
Specifies the string from which to obtain the left-most characters.
length
Specifies the number of characters to obtain.
Example :
Collapse SELECT LEFT('Marufuzzaman',5)
OutPut
Collapse Maruf
RIGHT()
Returns the right most characters of a string.
Syntax
Collapse RIGHT(string, length)
string
Specifies the string from which to obtain the left-most characters.
length
Specifies the number of characters to obtain.
Example :
Collapse SELECT RIGHT('Md. Marufuzzaman',12)
OutPut
Collapse Marufuzzaman
LTRIM()
Returns a character expression after it removes leading blanks.
Example :
Collapse SELECT LTRIM(' Md. Marufuzzaman')
OutPut
Collapse Md. Marufuzzaman
RTRIM()
Returns a character string after truncating all trailing blanks.
Example :
Collapse SELECT RTRIM('Md. Marufuzzaman ')
OutPut
Collapse Md. Marufuzzaman
REPLACE()
Returns a string with all the instances of a substring replaced by another substring.
Syntax
Collapse REPLACE(find, replace, string)
Find
Specifies the string that contains the substring to replace all instances of with another.
Replace
Specifies the substring to locate.
String
Specifies the substring with which to replace the located substring.
Example :
Collapse SELECT REPLACE('The codeProject is ?.','?', 'your development resource')
OutPut:
Collapse The codeProject is your development resource.
QUOTNAME()
Returns a Unicode string with the delimiters added to make the input string a valid Microsoft SQL Server delimited identifier.
Syntax
Collapse QUOTENAME ( 'character_string' [ , 'quote_character' ] )
Arguments
' character_string '
Is a string of Unicode character data. character_string is sysname and is limited to 128 characters. Inputs greater than 128 characters return NULL.
' quote_character '
Is a one-character string to use as the delimiter. Can be a single quotation mark ( ' ), a left or right bracket ( [ ] ), or a double quotation mark ( " ). If quote_character is not specified, brackets are used.
Return Types:
nvarchar(258)
Examples :
The following example takes the character string abc[]def and uses the [ and ] characters to create a valid SQL Server delimited identifier.
Collapse SELECT QUOTENAME('abc[]def')
OutPut:
Collapse [abc[]]def]
REVERSE()
Returns a character expression in reverse order.
Example :
Collapse SELECT REVERSE('namazzufuraM .dM')
Output:
Collapse Md. Marufuzzaman
CharIndex
returns the first occurance of a string or characters within another string. The Format of CharIndex is given Below:
CHARINDEX ( expression1 , expression2 [ , start_location ] )
Here expression1
is the string of characters to be found within expression2
. So if you want to search ij
within the word Abhijit
, we will use ij
as expression1
and Abhijit
as expression2
. start_location
is an optional integer argument which identifies the position from where the string will be searched. Now let us look into some examples :
Collapse SELECT CHARINDEX('SQL', 'Microsoft SQL Server')
OUTPUT:
Collapse 11
So it will start from 1 and go on searching until it finds the total string element searched, and returns its first position. The Result will be 0
if the searched string is not found.
We can also mention the Start_Location
of the string to be searched.
EXAMPLE:
Collapse SELECT CHARINDEX('SQL', 'Microsoft SQL server has a great SQL Engine',12)
So in the above example we can have the Output as 34 as we specified the StartLocation as 12, which is greater than initial SQL position(11).
As a contrast PatIndex
is used to search a pattern within an expression. The Difference between CharIndex
and PatIndex
is the later allows WildCard Characters.
PATINDEX ( '%pattern%' , expression)
Here the first argument takes a pattern with wildcard characters like '%' (meaning any string) or '_' (meaning any character).
For Example
PATINDEX('%BC%','ABCD')
Output:
Collapse 2
Another flexibility of PATINDEX is that you can specify a number of characters allowed within the Pattern. Say you want to find all of the records that contain the words "Bread", or "bread" in a string, You can use the following :
Collapse SELECT PATINDEX('%[b,B]read%', 'Tommy loves Bread')
In this example, we mentioned both b and B in square brackets. The Result will be 13 which is same if we have searched in 'Tommy loves bread'
.
Len is a function which returns the length of a string. This is the most common and simplest function that everyone use. Len Function excludes trailing blank spaces.
Collapse SELECT LEN('ABHISHEK IS WRITING THIS')
This will output 24, it is same when we write LEN('ABHISHEK IS WRITING THIS ')
as LEN doesnt take trailing spaces in count.
Stuff is another TSql Function which is used to delete a specified length of characters within a string and replace with another set of characters. The general syntax of STUFF is as below :
STUFF(character_expression1, start, length, character_expression2)
Character_Expression1
represents the string in which the stuff is to be applied. start
indicates the starting position of the character in character_expression1
, length
is the length of characters which need to be replaced. character_expression2 is the string that will be replaced to the start position.
Let us take an example :
Collapse SELECT STUFF('SQL SERVER is USEFUL',5,6,'DATABASE')
So the result will be :
SQL DATABASE is USEFUL
Substring
returns the part of the string from a given characterexpression. The general syntax of Substring is as follows :
SUBSTRING(expression, start, length)
Here the function gets the string from start to length. Let us take an example below:
Collapse SELECT OUT = SUBSTRING('abcdefgh', 2, 3)
The output will be "bcd".
Note : substring also works on ntext, VARCHAR, CHAR etc.
Anoter simple but handy function is Lower / UPPER. The will just change case of a string expression. For Example,
Collapse SELECT UPPER('this is Lower TEXT')
Output:
THIS IS LOWER TEXT