CHAPTER 9

image

Working with Strings

by Andy Roberts

This next set of recipes demonstrates SQL Server’s string functions. String functions provide a multitude of uses for your Transact-SQL programming, allowing for string cleanup, conversion between ASCII and regular characters, pattern searches, removal of trailing blanks, and much more. Table 9-1 lists the different string functions available in SQL Server.

Table 9-1. String Functions

Function Name(s) Description
CONCAT The CONCAT function concatenates a variable list of string values into one larger string.
ASCII and CHAR The ASCII function takes the leftmost character of a character expression and returns the ASCII code. The CHAR function converts an integer value for an ASCII code to a character value instead.
CHARINDEX and PATINDEX The CHARINDEX function is used to return the starting position of a string within another string. The PATINDEX function is similar to CHARINDEX, except that PATINDEX allows the use of wildcards when specifying the string for which to search.
DIFFERENCE and SOUNDEX The two functions DIFFERENCE and SOUNDEX both work with character strings to evaluate those that sound similar. SOUNDEX assigns a string a four-digit code, and DIFFERENCE evaluates the level of similarity between the SOUNDEX outputs for two separate strings.
LEFT and RIGHT The LEFT function returns a part of a character string, beginning at the specified number of characters from the left. The RIGHT function is like the LEFT function, only it returns a part of a character string beginning at the specified number of characters from the right.
LEN and DATALENGTH The LEN function returns the number of characters in a string expression, excluding any blanks after the last character (trailing blanks). DATALENGTH, on the other hand, returns the number of bytes used for an expression.
LOWER and UPPER The LOWER function returns a character expression in lowercase, and the UPPER function returns a character expression in uppercase.
LTRIM and RTRIM The LTRIM function removes leading blanks, and the RTRIM function removes trailing blanks.
NCHAR and UNICODE The UNICODE function returns the Unicode integer value for the first character of the character or input expression. The NCHAR function takes an integer value designating a Unicode character and converts it to its character equivalent.
REPLACE The REPLACE function replaces all instances of a provided string within a specified string with a new string.
REPLICATE The REPLICATE function repeats a given character expression a designated number of times.
REVERSE The REVERSE function takes a character expression and outputs the expression with each character position displayed in reverse order.
SPACE The SPACE function returns a string of repeated blank spaces, based on the integer you designate for the input parameter.
STUFF The STUFF function deletes a specified length of characters and inserts a designated string at the specified starting point.
SUBSTRING The SUBSTRING function returns a defined chunk of a specified expression.

The next few recipes will demonstrate examples of how string functions are used.

9-1. Concatenating Multiple Strings

Problem

You have a set of string values that you would like to concatenate into one string value. This is often a requirement when formatting names or addresses. In the database the name may be stored as separate first, middle and last names; however, you may wish to execute a query that returns “Last Name, First Name” and add the middle initial if it exists.

Solution

For this example, create a FullName column from the FirstName, MiddleName and LastName columns of the Person.Person table.

SELECT TOP 5
   FullName = CONCAT(LastName, ', ', FirstName, ' ', MiddleName)
FROM Person.Person p ;

The result of this query is:

FullName
-----------------------------------
Abbas, Syed E
Abel, Catherine R.
Abercrombie, Kim
Abercrombie, Kim
Abercrombie, Kim B

How it Works

The CONCAT function accepts a variable list of string values (at least two are required) and concatenates them into one string. A difference between the CONCAT function and using the + operator is how nulls are handled. The operator + will return NULL if either the left or right side of the operator is NULL. The CONCATfunction will convert NULL arguments to an empty string prior to the concatenation.

Take the following select statement that concatenates a FullName with three different approaches:

SELECT TOP 5
   FullName = CONCAT(LastName, ', ', FirstName, ' ', MiddleName),
                FullName2 = LastName + ', ' + FirstName + ' ' + MiddleName,
                FullName3 = LastName + ', ' + FirstName +
                   IIF(MiddleName IS NULL, '', ' ' + MiddleName)
FROM Person.Person p
WHERE MiddleName IS NULL ;

This query yields the following results:

FullName FullName2 FullName3
---------------- --------- -----------------------
Abercrombie, Kim NULL Abercrombie, Kim
Abercrombie, Kim NULL Abercrombie, Kim
Abolrous, Sam NULL Abolrous, Sam
Acevedo, Humberto NULL Acevedo, Humberto
Achong, Gustavo NULL Achong, Gustavo

The FullName Column used the CONCAT function as seen in the recipe. FullName2 uses the + operator. The + operator will always return NULL if one of its operands is NULL – because MiddleName is NULL for all rows then FullName2 is NULLfor all rows. Finally, the FullName3 column shows the logic that is encapsulated in the CONCATfunction. In this recipe’s example, 3 columns and two string literals are concatenated together using the CONCAT function. The MiddleName column is NULL for some rows in the table but no additional NULL handling logic is required when using CONCAT to generate the FullName string.

9-2. Finding a Character’s ASCII Value

Problem

Your application requires the ASCII values of a string’s characters or passes you ASCII values that you must assemble into a string.

Solution

This first example demonstrates how to convert characters into the integer ASCII value:

SELECT ASCII('H'),
   ASCII('e'),
   ASCII('l'),
   ASCII('l'),
   ASCII('o') ;

This returns:

72	101	108	108	111

Next, the CHAR function is used to convert the integer values back into characters again:

SELECT CHAR(72),
   CHAR(101),
   CHAR(108),
   CHAR(108),
   CHAR(111) ;

This returns:

H e l l o

How it Works

The ASCII function takes the leftmost character of a character expression and returns the ASCII code. The CHAR function converts the integer value of an ASCII code to a character value. The ASCII function only converts the first character of the supplied string. If the string is empty or NULL, ASCII will return NULL (although a blank, single-space value is represented by a value of 32).

In this recipe, the word “Hello” is deconstructed into 5 characters and then converted into the numeric ASCII values using the ASCII function. In the second T-SQL statement the processis reversed and the ASCII values are converted back into characters using the CHAR function.

9-3. Returning Integer and Character Unicode Values

Problem

Your application requires the Unicode values of a string’s characters or passes you Unicode values that you must assemble into a string.

Solution

The UNICODE function returns the Unicode integer value for the first character of the character or input expression. The NCHAR function takes an integer value designating a Unicode character and converts it to its character equivalent.

This first example converts single characters into an integer value representing the Unicode standard character code:

SELECT UNICODE('G'),
   UNICODE('o'),
   UNICODE('o'),
   UNICODE('d'),
   UNICODE('!') ;

This returns:

71 111 111 100 33

Next, the Unicode integer values are converted back into characters:

SELECT NCHAR(71),
   NCHAR(111),
   NCHAR(111),
   NCHAR(100),
   NCHAR(33) ;

This returns

G o o d !

How it Works

In this example, the string “Good!” is deconstructed one character at a time and then each character is converted into an integer value using the UNICODE function. In the second example, the integer values are reversed back into characters by using the NCHAR function.

9-4. Locating a Substring

Problem

You need to find out where a string segment or character pattern starts within the context of a larger string. For example, you need to find all of the street addresses that match a pattern you are looking for.

Solution

This example demonstrates how to find the starting position of a string within another string:

SELECT CHARINDEX('string to find','This is the bigger string to find something in.'),

This returns

20

That is, the first character of the first instance of the string “string to find” is the 20th character of the string that we are searching.

In some cases a character pattern must be found within a string. The following example returns all rows from the address table that contain the digit 0 preceding the word “Olive”

SELECT TOP 10
   AddressID,
   AddressLine1,
   PATINDEX('%[0]%Olive%', AddressLine1)
FROM Person.Address
WHERE PATINDEX('%[0]%Olive%', AddressLine1) > 0 ;

The results of this statement:

AddressID AddressLine1
--------- ------------------ ---
29048 1201 Olive Hill 3
11768 1201 Olive Hill 3
15417 1206 Olive St 3
24480 1480 Oliveria Road 4
19871 1480 Oliveria Road 4
12826 1803 Olive Hill 3
292 1803 Olive Hill 3
29130 2309 Mt. Olivet Ct. 3
23767 2309 Mt. Olivet Ct. 3
23875 3280 Oliveria Road 4

How it Works

The CHARINDEX function is used to return the starting position of a string within another string. The syntax is as follows:

CHARINDEX ( expressionToFind ,expressionToSearch[ , start_location ] )

CHARINDEX will sefrarch the string passed to expressionToSearch for the first instance of expressionToFind that exists after the optionally specified start_location.

This function returned the starting character position, in this case the 20th character, where the first argument expression was found in the second expression. Wildcards are not supported with CHARINDEX.

To use wildcards when searching for a substring use the PATINDEX function. Similar to CHARINDEX, PATINDEX allows the use of wildcards in the string you are searching for. The syntax for PATINDEX is as follows:

PATINDEX ( '%pattern%' ,expression )

PATINDEX returns the start position of the first occurrence of the search pattern, but unlike CHARINDEX, it does not contain a starting position option. Both CHARINDEX and PATINDEX return 0 if the search expression is not found in the expression to be searched.

image Note  In this example we showed the a small set of the wild card searches that may be used within PATINDEX. PATINDEX supports the same wildcard functionality as the LIKE operator. For further information see the Performing Wildcard Searches recipe in Chapter 1.

9-5. Determining the Similarity of Strings

Problem

You are designing a call center application and the agents look up customers by last name while speaking with the customer on the phone. The agents would like to guess at the spelling of the name to narrow the search results and then work with the customer to determine the appropriate spelling.

Solution

The two functions SOUNDEXand DIFFERENCE both work with character strings and evaluate the strings based on English phonetic rules.

Take the example where an agent hears the name “Smith”. SOUNDEX may be used to return all of the names that contain the same SOUNDEX value of the string “Smith”.

SELECT DISTINCT
SOUNDEX(LastName),
    SOUNDEX('Smith'),
    LastName
FROM Person.Person
WHERE SOUNDEX(LastName) = SOUNDEX('Smith') ;

This query returns the results:

                LastName
----- ----- -----------
S530 S530 Schmidt
S530 S530 Smith
S530 S530 Smith-Bates
S530 S530 Sneath

Note that “Smith” is returned, but also a number of names that may sound like the last name “Smith”.

Another way to look at the data would be to view the names that had the “least difference” from the search expression. The SQL Server DIFFERENCE function evaluates the phonetic similarity of two strings and returns a value from 0 (low similarity) to 4 (high similarity). If we look for last names with a phonetic similarity to “Smith”

SELECT DISTINCT
   SOUNDEX(LastName),
   SOUNDEX('smith'),
   DIFFERENCE(LastName, 'Smith'),
   LastName
FROM Person.Person
WHERE DIFFERENCE(LastName, 'Smith') = 4 ;

This query returns:

                         LastName
----- ----- - -----------
S530 S530 4 Smith
S530 S530 4 Smith-Bates
S530 S530 4 Sneath
S550 S530 4 Simon
S553 S530 4 Samant
S553 S530 4 Swaminathan

Note that the name “Schmidt” contains the same SOUNDEX value so is returned from the first query but is absent from the second result.

How it Works

The SOUNDEX function follows a set of rules originally created to categorize names based on the phonetic characteristics of the name rather than the spelling of that name. The soundex of a name consists of a letter – the first letter of that name – followed by three representing the predominant consonant sounds of that name.

Difference uses a variation of the soundex algorithm to return a rather course determination of the phonetic similarity of two strings – a range of 0 representing very low similarity to 5 representing very high similarity. Taking the Leftmost or Rightmost Part of a String

9-6. Returning the Left-Most Portion of a String

Problem

You have a string value and only need the first or last part of the string. For example, you have a report that will list a set of products but you only have room on the report to display the first 10 characters of the product name.

Solution

This recipe demonstrates how to return a subset of the leftmost and rightmost parts of a string. First take the leftmost (first) 10 characters of a string:

SELECT LEFT('I only want the leftmost 10 characters.', 10) ;

This returns:

I only wan

Next, take the rightmost (last) 10 characters of a string:

SELECT RIGHT('I only want the rightmost 10 characters.', 10) ;

This returns:

haracters.

The example in the problem statement describes taking the left 10 characters of the product name for a report. The following query is an example of how to accomplish this.

SELECT TOP 5
   ProductNumber,
   ProductName = LEFT(Name, 10)
FROM Production.Product ;

This query yields the following:

ProductNumber	ProductName
------------- -----------
AR-5381 Adjustable
BA-8327 Bearing Ba
BE-2349 BB Ball Be
BE-2908 Headset Ba
BL-2036 Blade

It is common that a string needs to be “padded” on one side or another. For example, the AccountNumber column in the Sales.Customer table is 10 characters consisting of “AW” plus 8 digits. The 8 digits include the CustomerID column padded with 0’s. A customer with the CustomerID 123 would have the account number “AW00000123”.

SELECT TOP 5
   CustomerID,
   AccountNumber = CONCAT('AW', RIGHT(REPLICATE('0', 8)
                   + CAST(CustomerID AS VARCHAR(10)), 8))
FROM Sales.Customer ;

This returns:

CustomerID	AccountNumber
---------- -------------
1         AW00000001
2         AW00000002
7         AW00000007
19         AW00000019
20         AW00000020

How it Works

The LEFT function returns the segment of the supplied character string that starts at the beginning of the string and ends at the specified number of characters from the beginning of the string. The RIGHT function returns the segment of the supplied character string that starts at the specified number of characters from the end of the string and ends at the end of the string.

This recipe demonstrates three examples of using LEFT and RIGHT. The first two examples demonstrate how to return the leftmost or the rightmost characters of a string value. The third example demonstrates how to the pad a string in order to conform to some expected business or reporting format.

When presenting data to end users or exporting data to external systems, you may sometimes need to preserve or add leading values, such as leading zeros to fixed-length numbers or spaces to varchar fields. CustomerID was zero-padded by first concatenating 8 zeros in a string to the converted varchar(10) value of the CustomerID. Then, outside of this concatenation, RIGHT was used to grab the last 8 characters of the concatenated string (thus taking leading zeros from the left side with it, when the CustomerID fell short of 8 digits).

9-7. Returning Part of a String

Problem

You are creating a call-center report that includes aggregations of data by area code and exchange of phone numbers in the system. You need to look at characters 1-3 and 5-7 of a phone number string. Solution

Use the left and substring functions to pull out the desired characters of the phone number.

SELECT TOP 3
   PhoneNumber,
   AreaCode = LEFT(PhoneNumber, 3),
   Exchange = SUBSTRING(PhoneNumber, 5, 3)
FROM       Person.PersonPhone
WHERE      PhoneNumber LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' ;
PhoneNumber AreaCode Exchange
----------- -------- --------
100-555-0115 100 555
100-555-0124 100 555
100-555-0137 100 555

How it Works

The SUBSTRING function returns a defined segment of a specified string expression. The syntax is as follows:

SUBSTRING ( expression, start, length )

The first argument of this function is the character expression that contains the desired segment. The second argument defines the starting position within “expression” of the segment to return. The third argument is the length, in characters, of the segment to be returned.

In this recipe, the SUBSTRING function is used to extract digits 5-7 from a longer phone number. The first parameter is the phone number. The second parameter is the starting position of the string – the 5th character in the string. The third parameter indicates how many characters to extract – 3.

There are multiple phone number formats stored in the database and we are only interested in the format XXX-XXX-XXXX. The WHERE clause of the SELECT statement uses wildcards with the LIKE operator to filter the results to only numbers that meet this format.

9-8. Counting Characters or Bytes in a String

Problem

Your application requires you to return the length or size (in bytes) of strings that you return from a stored procedure.

Solution

This first example returns the number of characters in the Unicode string (Unicode data takes two bytes for each character, whereas non-Unicode takes only one):

SELECT LEN(N'She sells sea shells by the sea shore. ') ;

This returns

38

This next example returns the number of bytes in the Unicode string:

SELECT DATALENGTH(N'She sells sea shells by the sea shore. ') ;

This returns

80

How it Works

The LEN function returns the number of characters in a string expression excluding any blanks after the last character (trailing blanks). DATALENGTH returns the number of bytes used for an expression (including trailing blanks.

This recipe uses a Unicode string defined by prefixing the string with an N:

N'She sells sea shells by the sea shore. '

The number of characters for this string is 38 according to LEN as there are 38 characters starting with the “S” in “She” and ending with the “.”. The spaces following the “.” are not counted by LEN. DATALENGTH returns 80 bytes. SQL Server uses the Unicode UCS-2 encoding form, which consumes 2 bytes per character stored and the trailing spaces are counted – (38 + 2) * 2.

image Note  We typically use DATALENGTH to find the number of bytes in a string; however, DATALENGTH will determine the length of any data type. Take the follow query for example:

SELECT DATALENGTH(123),
    DATALENGTH(123.0),
    DATALENGTH(GETDATE()) ;

We pass an int, a numeric and a datetime value into DATALENGTH and DATALENGTH returns 4, 5, and 8 ­respectively.

9-9. Replacing Part of a String

Problem

You need to replace all instances of a string value within a larger string value. For example, the name of a product has changed and you must update product descriptions with the new product name.

Solution

This example replaces all instances of the string “Classic” with the work “Vintage”:

SELECT REPLACE('The Classic Roadie is a stunning example of the bikes that AdventureWorks have been producing for years – Order your classic Roadie today and experience AdventureWorks history.', 'Classic', 'Vintage'),

This returns:

The Vintage Roadie is a stunning example of the bikes that AdventureWorks have been producing for years – Order your Vintage Roadie today and experience AdventureWorks history.

How it Works

The REPLACE function searches a source string for all instances of a provided search pattern and replaces them with the supplied replacement string. A strength of REPLACE is that unlike PATINDEX and CHARINDEX that return one location where a pattern is found, REPLACE finds and replaces all instances of the search string within a specific character string. The syntax for REPLACE is as follows:

REPLACE ( string_expression , search_string , replacement_string );

The first argument, string_expression, is the string that will be searched. The second argument, search_string, is the string to be removed from the original string. The third argument, replacement_string, is the string to use as a replacement to the search string.

In this example we searched the product description for all instances of the string “Classic” and replaced them with the string “Vintage”.

REPLACE can also be used to remove portions of a string. If the replacement_string parameter is an empty string (''), REPLACE will remove search_string from string_expression and replace it with 0 characters. Note, in this case this is an empty string ('') not a NULL value. If replacement_string is NULL the the output of REPLACE will always be NULL.

9-10. Stuffing a String into a String

Problem

You need to insert a string into another string.

Solution

This example replaces a part of a string and inserts a new expression into the string body:

SELECT STUFF ( 'My cat''s name is X. Have you met him?', 18, 1, 'Edgar' );

This returns:

My cat's name is Edgar. Have you met him?

image Note  Do you notice the two single quotes in the query above? This is not double quote but an “escaped” apostrophe. String literals in SQL Server are identified by single quotes. To specify an apostrophe in a string literal you need to “escape” the apostrophe by placing two apostrophe’s next to each other. As you can see in the results listing: “cat’’s” is displayed as “cat’s”.

How it Works

The STUFF function deletes a specified length of characters and inserts a designated string at the specified starting point. The syntax is as follows:

STUFF ( character_expression, start, length, character_expression )

The first argument of this function is the character expression to be modified. The second argument is the starting position of the string to be inserted. The third argument is the number of characters to delete within the string in the first argument. The fourth argument is the actual character expression that you want to insert.

The first character expression in this recipe is “My cat’s name is X. Have you met him?”. The start value is 18, meaning the replacement will occur at the 18th character in the string (“X”). The length parameter is 1 meaning only one character at position 18 will be deleted. The last character expression is Edgar. This is the value to stuff into the string.

If a 0 length parameter is specified the STUFF function simply inserts the second string into the first string before the character specified with the start argument. For example:

SELECT STUFF ( 'My cat''s name is X. Have you met him?', 18, 0, 'Edgar' );

This returns:

My cat's name is EdgarX. Have you met him?

If an empty string (‘’) is specified for the second character expression the STUFF function deletes the characters starting with the character specified with the start argument and continuing for the number of characters specified in the length argument. For example:

SELECT STUFF ( 'My cat''s name is X. Have you met him?', 18, 8, '' );

This returns:

My cat's name is you met him?

9-11. Changing Between Lower- and Uppercase

Problem

You have some text that, for reporting purposes, you would like to return as all upper case or all lower case.

Solution

The following query shows the value of DocumentSummary for a specific row in the Production.Document table:

SELECT DocumentSummary
FROM Production.Document
WHERE FileName = 'Installing Replacement Pedals.doc';

This returns the following sentence-case value:

DocumentSummary
------------------------------------ Detailed instructions for replacing pedals with Adventure Works Cycles replacement pedals. Instructions are applicable to all Adventure Works Cycles bicycle models and replacement pedals. Use only Adventure Works Cycles parts when replacing worn or broken components.

This first example demonstrates setting values to lowercase:

SELECT LOWER(DocumentSummary)
FROM Production.Document
WHERE FileName = 'Installing Replacement Pedals.doc';

This returns:

detailed instructions for replacing pedals with adventure works cycles replacement pedals. instructions are applicable to all adventure works cycles bicycle models and replacement pedals. use only adventure works cycles parts when replacing worn or broken components.

Now for uppercase:

SELECT UPPER(DocumentSummary)
FROM Production.Document
WHERE FileName = 'Installing Replacement Pedals.doc';

This returns:

DETAILED INSTRUCTIONS FOR REPLACING PEDALS WITH ADVENTURE WORKS CYCLES REPLACEMENT PEDALS. INSTRUCTIONS ARE APPLICABLE TO ALL ADVENTURE WORKS CYCLES BICYCLE MODELS AND REPLACEMENT PEDALS. USE ONLY ADVENTURE WORKS CYCLES PARTS WHEN REPLACING WORN OR BROKEN COMPONENTS.

How it Works

The LOWER function returns a character expression in lowercase, and the UPPER function returns a character expression in uppercase. If a character in the string is not case-convertible the character is returned with no conversion. For example, look at the string with Thai characters used earlier in this chapter:

SELECT UPPER (N'เป็นสายอักขระ unicode'),

This returns:

เป็นสายอักขระ UNICODE

Because there is no upper and lower case distinction for the Thai characters, UPPER and LOWER produce no affect on them.

image Tip   There is not a proper case function built into SQL Server; however, Chapter 20 discusses scalar user-defined functions. Using a user defined function would be a great technique to create a proper case function.

The first example demonstrates the LOWER function and returns a character expression in lowercase. The second example demonstrates the UPPER function and returns a character expression in uppercase. In both cases the function takes a single argument: the character expression containing the case to be converted to either upper- or lowercase.

9-12. Removing Leading and Trailing Blanks

Problem

You have text entered through an application that may contain leading or trailing blanks and you would like to remove these blanks before storing the data.

Solution

This first example demonstrates removing leading blanks from a string:

SELECT CONCAT('''', LTRIM(' String with leading and trailing blanks. '), '''' );

This returns:

'String with leading and trailing blanks. '

This second example demonstrates removing trailing blanks from a string:

SELECT CONCAT('''', RTRIM(' String with leading and trailing blanks. '), '''' );

This returns:

' String with leading and trailing blanks.'

The final example shows that LTRIM and RTRIM may be used together to remove blanks from both ends of a string

SELECT CONCAT('''', LTRIM(RTRIM(' String with leading and trailing blanks ')), '''' );

This returns:

'String with leading and trailing blanks'

How it Works

Both LTRIM and RTRIM take a single argument—a character expression that is to be trimmed. The function then trims the leading or trailing blanks. Note that there is not a TRIM function (as seen in other programming languages) that can be used to remove both leading and trailing characters. To do this, you must use both LTRIM and RTRIM in the same expression.

9-13. Repeating an Expression N Times

Problem

Often when testing an application’s user interface you will need to populate sample data into a database that fills the database columns to the maximum length of character data to ensure that the UI will properly display larger strings. Generally the character ‘W’ is used as it is a wide character.

Solution

Use the replicate function to produce a string of 30 character W’s.

SELECT REPLICATE ('W', 30) ;

This returns

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW

Use the replicate function to produce a string of 30 repetitions of the string ‘Z_’.

SELECT REPLICATE ('W_', 30) ;

This returns:

W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_W_

How it Works

The REPLICATE function repeats a given character expression a designated number of times. The syntax is as follows:

REPLICATE ( character_expression,integer_expression )

The first argument is the character expression to be repeated. The second argument is the integer value representing the number of times the character expression is to be repeated.

In this recipe’s first example the letter ‘W’ is supplied as the character expression and is as repeated 30 times. The second example shows that REPLICATE can repeat string values and not only single characers. Use REPLICATE to repeat values rather than having to enter the string literals manually.

9-14. Repeating a Blank Space N Times

Problem

You are formatting a set of values for display and you would like the values to be returned as a one column result set and aligned in 20 character columns.

Solution

This example demonstrates how to repeat a blank space a defined number of times to align the values onto 20-character boundaries:

DECLARE @string1 NVARCHAR(20) = 'elephant',
    @string2 NVARCHAR(20) = 'dog',
    @string3 NVARCHAR(20) = 'giraffe' ;
SELECT *
FROM ( VALUES
    ( CONCAT(@string1, SPACE(20 - LEN(@string1)), @string2,
    SPACE(20 - LEN(@string2)), @string3,
    SPACE(20 - LEN(@string3))))
 ,
    ( CONCAT(@string2, SPACE(20 - LEN(@string2)), @string3,
    SPACE(20 - LEN(@string3)), @string1,
    SPACE(20 - LEN(@string1)))) ) AS a (formatted_string) ;

This returns:

formatted_string
-------------------------------------elephant dog giraffe
dog giraffe elephant

How it Works

The SPACE function returns a string of repeated blank spaces, based on the integer you designate for the input parameter. This is the same functionality as the REPLICATE function only the character to replicate is a constant.

In this recipe there are values that should be returned in one column of text aligned to 20 character boundaries. Each values is concatenated with a number of spaces equal to 20 – the length of the string.

The maximum return value for the SPACE function is 8,000 bytes.

9-15. Reversing the order of Characters in a String

Problem

You have the fully qualified file name and would like to split the string into path and filename.

Solution

In this example the files in the current database are broken out into paths and filenames. Find the last backslash (‘’) character in the string and use that position as the basis for the boundary between path and filename.

SELECT Path = LEFT(filename, LEN(filename) - CHARINDEX('', REVERSE(filename)) + 1),
   FileName = RIGHT(filename, CHARINDEX('', REVERSE(filename)) - 1)
FROM sys.sysfiles ;

This example returns the following results (In this example the paths and filenames will differ depending on the database file names and locations.)

Path	FileName
---------------- ---------------------------
E:SqlDatabases AdventureWorks2012_Data.mdf
E:SqlDatabases AdventureWorks2012_log.ldf

How it Works

The REVERSE function takes a character expression and outputs the expression with each character position displayed in reverse order.

By using CHARINDEX on the reversed string, instead of finding the first occurrence of the character the last occurrence is returned. LEFT and RIGHT are used to split the string at the identified location.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.121.79