SqlTutorial-1 : Lesson-11 : Class-2
Microsoft SQL Server Training: Free Online-Learning Classes (OLC) for T-SQL
Built-in Sql functions: String functions
INDEX - (21 functions)
1. Type Conversion:
ASCII to CHAR or vice versa: ASCII() & CHAR() methods.
UNICODE to CHAR or vice versa : UNICODE() & NCHAR() methods.
Tostring() : STR()
2. Extracting Sub-string
Corner-ended sub-strings: LEFT(), RIGHT(),
Any positional sub-string SUBSTRING(),
3. Find and replace
To find: CHARINDEX()
Pattern matchig with wild-cards:PATINDEX()
To replace: REPLACE()
4. String Comparision
Spelling-based comparision DIFFERENCE()
Sond-based Comparision SOUNDEX();
5. Case-Conversions
To lower case :LOWER()
To upper case: UPPER()
6. Space Trimming and padding
To trimming leading & trailing spaces: LTRIM() & RTRIM()
To inserting blank space(s): SPACE()
To inserting text: STUFF()
7. Determining length and Reverse
Length of string: LEN()
Reverse of string: REVERSE()
1. Type-Conversion functions
ASCII():
Returns the ASCII integer value of the leftmost character of a string.
Syntax
ASCII ( character_expression );
Converting Aphanumeric characters to ASCII-code.
SELECT ASCII('H'), ASCII('e'), ASCII('l'), ASCII('l'), ASCII('o') => 72 101 108 108 111
Converting Numeric letter to ASCII-Code....
SELECT ASCII(CHAR(4)) => 4
If multiple chars included then first char only converts
SELECT ASCII('abcdef') => 97
CHAR():
Converts an integer ASCII code to a character.; reverse of ASCII().
Syntax
CHAR ( integer_expression )
Finding character for ASCII-Code 97;
SELECT CHAR(97)=> 'a'
Display text with single quotation mark as 'Hello' or "Hello"
SELECT CHAR(39) + 'Hello' + CHAR(39) -- use 34 for "
Used to format the output. (Char(10)= ‘\n’, Char(9)=’\t’ , Char(‘\r’) );
e.g, Display record column-wise:
Select "MyRecord"= sname + CHAR(10) + convert(char(3), rollNo))
FROM student
WHERE sname=’Abcd’
Display record column-wise and terminate each record with line.
SELECT "MyRecords"= sname + CHAR(10) + convert(char(3),rollNo) +
CHAR(10)+ convert(char(3),Total) +
CHAR(10)+ ‘-----------------------------‘
STR():
Converts a numeric value to a string. Similar to STR(5)= CONVERT(CHAR(1), 5)
It accepts three arguments: the numeric value, the overall length, and the number of
decimal positions.
Syntax: STR(float_expression, character_length, number_of_decimal_places)
If the integer part of the number and decimal positions is shorter than the overall length,
the result is left-padded with spaces.
SELECT STR(123.4, 8, 4) è 23.4000
SELECT STR(100.325,7,2) è 100.33
SELECT STR(100.325,7) è100
SELECT STR(1, 6, 4) è 1.0000
SELECT STR(11111111, 10, 4) è 11111111.0
2. Extracting Sub-string
LEFT() :
Returns sub-string with given length from the left-hand side of given string.
Syntax:
LEFT ( character_expression , integer_expression )
To extract N-number of chars from left.
SELECT LEFT('1234',1)=> 1
SELECT LEFT('1234',2)=>12
SELECT LEFT('1234',3)=> 123
SELECT LEFT('welcome to www.abc.com', 8) => welcome
You can use it to perform pattern matching.
E.g., Find the employees whose name beings with 'A' letter.
SELECT *
FROM dbo.Customers
WHERE LEFT(Cname, 1) = N'A';
RIGHT():
Returns sub-string with given length from the right-hand side of given string.
Syntax:
RIGHT( character_expression , integer_expression )
To extract N-number ofchars from right
SELECT LEFT('1234',1)=>4
SELECT LEFT('1234',2)=>34
SELECT LEFT('1234',3)=>234
You can use it to perform pattern matching.
Q: Find the employees whose name ends with ‘n’ letter.
SELECT *
FROM dbo.Customers
WHERE RIGHT(Cname, 1) = N'n';
SUBSTRING():
Returns a part of given string.
Syntax:
SUBSTRING(string, start_position, length)
Extracting part of given string:
SELECT SUBSTRING("ABCDEFGH",2,3)èBCD
Extracting first word only.
SELECT SUBSTRING('Welcome Hello', 1, CHARINDEX(' ', 'Welcome Hello') - 1) => Welcome
To extracting all words except first.
SELECT SUBSTRING(@FullName, CHARINDEX(' ', @FullName) + 1, LEN(@FullName))
=> If @FullName=‘ The SQL Server 2005’, then output=’SQL Server 2005’
3. Find and Replace string
CHARINDEX():
Returns 0 if no-match, otherwise position of found substring. Comparison is case-insensitive basis.
Syntax
CHARINDEX(substring,SuperString,[searchPosition])
Where return Value always < searchPosition
Examples
SELECT CHARINDEX(' ', 'welcome abcd ') => 8
SELECT CHARINDEX('sql', ' SQL Server') => 2
SELECT CHARINDEX(‘AB’,’ABCDEF’,3); => 0
//Because after 3rd letter no ‘AB’
You can search any kind of letter.
select CHARINDEX('-', '(559) 555-1212')=> 10
PARTINDEX():
Searching strings within another string using wild-card characters. Wild-card
characters: “%”= any no. of chars & “_” = Any single char.
Syntax:
PATINDEX ( '%pattern%' , expression )
Examples:
SELECT PATINDEX('%yahoo%','This is www.yahoo.com') => 13
SELECT PATINDEX('%567%', '0123456789') => 6
SELECT PATINDEX('%v_r%', 'SQL Server') => 8
REPLACE():
Replaces the all occurrence of given string with sub-string.
Syntax
REPLACE(MainString, string_to_Find, String_to_replace)
Examples:
SELECT REPLACE("www.yahoo.com yahoo","yahoo","YAHOO")
=> www.YAHOO.com YAHOO
4. STRING COMPARISION
DIFFERENCE()
Returns an integer value that indicates the difference between the SOUNDEX
value of two character expressions. i.e,DIFFERENCE(s1,s2) = ABS(SOUNDEX(s1) – SOUNDEX(s2))
The return value is between 0-4 reflects closeness of two strings. 4 means perfect match and close and 0 means poorly close.
Syntax
DIFFERENCE (string1,string2)
Examples:
Actually it differentiates the string based on pronunciation; not on spelling nor case difference. E.g.,DIFFERENCE(sion, shun)è4 (i.e, same no difference)
SELECT DIFFERENCE('Dewson', 'Joosun') => 3
SELECT DIFFERENCE('aaaa','1111') => 0
SELECT DIFFERENCE('Dewson', 'aaaa') => 1
SELECT DIFFERENCE('Welcome', 'welcom') =>4
SELECT DIFFERENCE('Welcome', 'wecom') => 3
SELECT DIFFERENCE('To', 'Two') => 4(i.e,perfect match)
SELECT DIFFERENCE('nite', 'knight') => 1 (i.e,low)
SELECT DIFFERENCE("Kathy Ward","kathy WARD") => 4
SELECT DIFFERENCE("KATHY Ward","Cathy Ward") => 3
SELECT DIFFERENCE("KATHY Ward","Cathie Ward")=> 3
SOUNDEX():
Returns a four-character(SOUNDEX) code to evaluate the similarity of two strings.
Internally DIFFERENCE() uses SOUNDEX() to evaluating string comparison.
Examples
SELECT SOUNDEX(‘tion’) => S500
SELECT DIFFERENCE(SOUNDEX('tion'), SOUNDEX('tion')) => 4
SELECT SOUNDEX("Robin Dewson")=SOUNDEX("Robyn Jewshoon")
=> R150 R10
SELECT SOUNDEX('Fleas'),SOUNDEX('Fleece'), SOUNDEX('Peace'),SOUNDEX('Peas')
=> 420 420 400 400
SELECT CASE
WHEN SOUNDEX('Robin Dewson')=SOUNDEX('Robyn Jewshoon')
THEN 'EQUAL' ELSE 'UN-EQUAL'
END
=> EQUAL
5. CASE CONVERSION
LOWER()
Returns lower case string for given string.
Examples
SELECT LOWER('ABCDEE') => abcdee
UPPER()
Returns upper case string for given string.
Examples
SELECT UPPER(LOWER('abCDE')) => ABCDE
Changing to Sentence case
SELECT UPPER(LEFT("this Is a tEst.",1)+
LOWER(SUBSTRING("this Is a tEst.",2,20))
=> This is a test.
6.Space Trimming and Padding
LTRIM() and RTRIM()
Return the trimmed string of given string.
SELECT LTRIM(‘ abcd’) => abcd
SELECT RTRIM(‘WEL ‘)+LEFT(‘ COME’) => WELCOME
SPACE():
To get given no. of blank spaces.
SELECT 'Give me some' + SPACE(6) + 'space.'
STUFF()
positional based insertion/replacement of text.
Syntax:
STUFF(OriginalString, position, no_of_overwrites, subs-string)
For replacing “BCD”with "sho"
SELECT STUFF('ABCDEFGHIJKL', 2, 3, ' sho') => AshoEFGHIJKL
For inserting 'sho' after D
SELECT STUFF('ABCDEFGHIJKL', 4, 0, 'sho') => ABCshoDEFGHIJKL
7. Determining Length and Reverse
LEN()
Returns the size of given string including blank spaces. bigint if expression is of the varchar(max), nvarchar(max) or varbinary(max) data types; otherwise, int.
Syntax:
LEN( string_expression )
Examples:
select LEN('SQL Server')=>10
REVERSE()
Returns the reverse of given string.
Syntax
REVERSE( char expression)
Exampels:
SELECT REVESE(‘abc’) =>cba
SELECT Name, REVERSE(Name)as NameReversed
FROM employee
Thanks for sharing this amazing blog
ReplyDelete.Net Online Training Bangalore
Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time sql server dba online training
ReplyDeleteExtremely useful information which you have shared here Best online Software Training Institute and career consultancy in Noida
ReplyDelete