laika222
10/27/2016 - 6:12 PM

STRING Operations, SUBSTRING, CHARINDEX, REPLACE, CONCAT, LEFT, RIGHT, UPPER, LOWER

How to select various parts of a string of characters.

-- strings are placed within single quotes.
SELECT 'This is a string.'

-- placing an N before the first quote allows you do deal with a unicode string.
-- unicode allows for characters outside the normal ASCII set (ie foreign characters).
-- using this N is a best practice in case your database contains non-ASCII characters.
SELECT N'This is a string.'

/***********************************
LIKE
************************************/

-- LIKE allows you to search for patterns. This can be used with wildcards
SELECT * from T_APPEAL WHERE description LIKE '%Annual Fund%'

/***********************************
WILDCARDS
************************************/

-- you can use wildcards when searching

-- '%'' searches for any number of wildcard characters, including no characters. 
-- Often used at beginning and end of strings if you don't know where the pattern will be found within the text.
-- example below will search for any number of characers between the 'o' and 'c', and any number after the 't'.
SELECT * from T_APPEAL WHERE name LIKE 'pro%ct%'

-- '_' searches for a single wildcard character.
SELECT * from T_APPEAL WHERE name LIKE 'mcm_n'

-- placing brackets and a list of characters allows you to search for wilcards that use those characters.
-- in example below, it searches for strings that start with either '2', 'F', or 'C' as the first character
select * from T_Appeal
WHERE DESCRIPTION LIKE '[2FC]%'

-- you can search for a wildcard character range using brackets and a dash.
-- example below searches for strings where first character is a digit (0-9 being all of the digits)
select * from T_Appeal
WHERE DESCRIPTION LIKE '[0-9]%'

-- character range wildcards also work with alpha characters
select * from T_Appeal
WHERE DESCRIPTION LIKE '[A-F]%'

/***********************************
ESCAPING CHARACTERS
************************************/

-- you can escape characters using either brackets or the ESCAPE keyword.
-- this is helpful when you want to search for characters that are used as wildcards.

-- brackets can escape a character such as the '_' below
select * from T_Appeal
WHERE DESCRIPTION LIKE '[_]Annual Fund' 

-- you can also place an escape character prior to the character to be escaped, and then define
-- the escape character using the ESCAPE keyword.
-- below, the '!' acts as the escape character, and is placed right before the '_' being escaped
select * from T_Appeal
WHERE DESCRIPTION LIKE '!_Annual Fund' ESCAPE '!'

/***********************************
STRING FUNCTIONS
************************************/

-- SUBSTRING - Select characters from within a string of characters - format is SUBSTRING(column name, number of characters from the left at which to start, number of characters to select going from the starting point). Example below says to pull from Company column, start on the second character from the left, select three characters moving to the right from the starting point.
SELECT SUBSTRING(Company,2,3)   
FROM Orders2;   

-- CHARINDEX - tells you at which character from the left you will find the character or phrase you're looking for starts - the result will be a number like 11 (phrase starts 11 characters in from the left), format is (expression to find, expression to search, number of characters from the left to start at). The result is a number. For instance, 11 means the phrase you're looking for starts at the 11th character of the string. 0 means the phrase wasn't found.
SELECT CHARINDEX('search for this phrase',string to be searched (can be column name), number from left to start searching) 
FROM customers;

-- CHARINDEX example that searches for first instance of '2'. Result is 2.
SELECT CHARINDEX('2', '1232526236');

-- CHARINDEX example that searches for first instance of '2' starting at the third character 
-- in the string. Result is 4.
SELECT CHARINDEX('2', '1232526236', 3);
  
-- CHARINDEX example that uses subquery to search for second instance of '2'. This uses a substring to find the first instance of '2' (at position 2), then adds one to get 3, and uses three as the starting point to search for '2', which shows up at position 6. The second statement shows how this would be done using a column name rather than including the string in the query.
SELECT CHARINDEX ('2', '12513252252663', (SELECT CHARINDEX('2', '12513252252663') + 1));   

SELECT CHARINDEX ('a', Notes, (SELECT CHARINDEX('a', Notes) + 1))
FROM eventtest;   

/*
REPLACE - Select and replace characters from a string - format is 
REPLACE(text of string you want to replace, which character(s) you want to replace, 
what character(s) you want to replace it with). To remove a character(s), replace it 
with '' with nothing in-bewteen the quotes. In example below, 'test*2' will be returned 
as 'test--2'.

REPLACE removes all instances within the string, as opposed to STUFF which replaces just a certain
specified section of the string.
*/
SELECT REPLACE('test*2', '*', '--')

-- CONCAT - Combines two or more strings into a single string - format is CONCAT('string 1', 'string 2', 'string 3'). Example below shows a simple concatenation, followed by a concatenation using multiple SELECT statements.
SELECT CONCAT('This ', 'is ', 'a ', 'sentence.');

SELECT CONCAT((SELECT CustomerID from orders1 WHERE OrderID = 1), ' ', (SELECT OrderDate from orders1 WHERE OrderID = 2), ': ', 'this is the result');

-- LEFT - Select characters from the left of a string of characters - format is LEFT(column name, number of characters to select from the left). Example below says to pull from Company column, select 2 characters starting from the left (beginning) of the string.
SELECT LEFT(Company,2)   
FROM Orders2;   

-- RIGHT - Select characters from the right of a string of characters - format is RIGHT(column name, number of characters to select from the right). Example below says to pull from Company column, select 3 characters starting from the right (end) of the string.
SELECT RIGHT(Company,3)   
FROM Orders2;  

-- UPPER - Select a string and converts all characters to upper case. For example, a result of 'suzuki01' would be returned as 'SUZUKI01'.
SELECT UPPER((SELECT playerID from Batting where ID = 262));

-- LOWER - Select a string and converts all characters to upper case. For example, a result of 'SUZuki01' would be returned as 'suzuki01'.
SELECT LOWER((SELECT playerID from Batting where ID = 262));

-- LEFT TRIM - Removes all spaces from beginning of string before non-space characters begin. In example below, '   test   ' will be returned as 'test   '.
SELECT LTRIM('   test   ');

-- RIGHT TRIM - Removes all spaces from end of string after non-space characters end. In example below, '   test   ' will be returned as '   test'.
SELECT RTRIM('   test   ');

-- TRIM (MySQL only) - Removes all spaces from beginning and end of string. In example below, '   test   ' will be returned as 'test'.
SELECT TRIM('   test   ');

-- LEFT and RIGHT TRIM (SQL Server only) - Removes all spaces from beginning and end of string by using a combination of LTRIM and RTRIM. In example below, '   test   ' will be returned as 'test'.
SELECT LTRIM(RTRIM('    test    '));

-- LEN returns the length of a string. Trailing spaces in the string are removed.
SELECT LEN('this string');

/*
DATALENGTH returns number of bytes of a string. Does not remove trailing spaces (those are counted).
For a normal string with no trailing spaces, this will return the same value as LEN.
For a unicode string, this will count 2 bytes for each character.
*/

SELECT DATALENGTH('this a normal string  '); --normal string, result is 23.

SELECT DATALENGTH(N'this a unicode string  '); --unicode string, result is 46 (2 bytes per characer)

-- REPLICATE takes a string and duplicates it. Result below is 'This is a string This is a string This is a string '
SELECT REPLICATE('This is a string ',3) AS 'Replicated'

/*
STUFF takes a string and replaces it. You specify a string, a starting postion, 
the number of characters to remove, and the string you want to replace it with., then a starting posting, and a number of characters to delete.

REPLACE removes all instances within the string, as opposed to STUFF which replaces just a certain
specified section of the string.
*/
SELECT STUFF('ABCDEFG', 2, 3, '123456')

/*
Results:

(No column name)
A123456EFG
*/