Showing posts with label sql server. Show all posts
Showing posts with label sql server. Show all posts

Thursday, 16 August 2012

SSAS MDX Queries part 2

Children Property
select
[Measures].[Internet Sales Amount] on columns,
[Customer].[Customer Geography].[Country].[France].children on rows
from
[Adventure Works]

Exists Function
select
exists([Customer].[Customer Geography].[Customer].[Crystal Zheng],[Customer].[Customer Geography].members) on columns,
[Measures].[Sales Amount] ON ROWS
from
[Adventure Works]

Parent Function
select
[Measures].[Internet Sales Amount]on columns,
[Customer].[Customer Geography].[Customer].[Crystal Zheng].parent.parent on rows
from
[Adventure Works]

Ancestor Function
select
[Measures].[Internet Sales Amount] on columns,
ancestor([Customer].[Customer Geography].[Customer].
[Crystal Zheng],[Customer].[Customer Geography].[City]) on rows
from
[Adventure Works]

select
[Measures].[Internet Sales Amount]on columns,
ancestor([Customer].[Customer Geography].[Customer].[Crystal Zheng],2) on rows
from
[Adventure Works]

Ascendants Function
 Returns all the ancestors of a specified member and the member itself up to the root of the member's hierarchy. Note that the specified member is returned first, then its parent, its grandparent and so on.

Example :
select
[Measures].[Internet Sales Amount]on columns,
ascendants([Customer].[Customer Geography].[Postal Code].&[OX14 4SE]&[Oxford]&[ENG]) on rows
from
[Adventure Works]

Ascendants with Hierarchize Function
Select
[Measures].[Internet Sales Amount]on columns,
hierarchize(ascendants([Customer].[Customer Geography].[Customer].[Crystal Zheng])) on rows
from
[Adventure Works]

FirstChild Function
select
[Measures].[Internet Sales Amount] on columns,
[Customer].[Customer Geography].[Customer].[Crystal Zheng].parent.firstchild on rows
from
[Adventure Works]

LastChild Function
select
[Measures].[Internet Sales Amount] on columns,
[Customer].[Customer Geography].[Customer].[Crystal Zheng].parent.lastchild
on rows
from
[Adventure Works]

Lastsibling  Function
select [Measures].[Internet Sales Amount]on columns,
[Customer].[Customer Geography].[Customer].[Crystal Zheng].lastsibling on rows
from [Adventure Works]

Descendants Function 
Syntax:

  1. DESCENDANTS( «Member»[, «Level»[, «Desc_flags»]] )
  2. DESCENDANTS( «Member»,«Distance»[, «Desc_flags»] ) 
According to MSDN, descendants MDX function returns the set of descendants of a member at a specified level or distance, optionally including or excluding descendants in other levels.
Desc_flags has 8 different flags option for returning set of descendant members. Here is description of each option mentioned in MSDN.
 
SELF Returns only descendant members from the specified level or at the specified distance. The function includes the specified member, if the specified level is the level of the specified member.

AFTER Returns descendant members from all levels subordinate to the specified level or distance.

BEFORE Returns descendant members from all levels between the specified member and the specified level, or at the specified distance. It includes the specified member, but does not include members from the specified level or distance.

BEFORE_AND_AFTER Returns descendant members from all levels subordinate to the level of the specified member. It includes the specified member, but does not include members from the specified level or at the specified distance.

SELF_AND_AFTER Returns descendant members from the specified level or at the specified distance and all levels subordinate to the specified level, or at the specified distance. S

SELF_AND_BEFORE Returns descendant members from the specified level or at the specified distance, and from all levels between the specified member and the specified level, or at the specified distance, including the specified member.

SELF_BEFORE_AFTER Returns descendant members from all levels subordinate to the level of the specified member, and includes the specified member. 


Examples :

select
[Measures].[Internet Sales Amount] on columns,
descendants([Customer].[Customer Geography].[Country].&[United Kingdom],[Customer].[Customer Geography].[City])on rows
from [Adventure Works]

select
[Measures].[Internet Sales Amount] on columns,
descendants([Customer].[Customer Geography].[Country] .[France],[Customer].[Customer Geography].[City],self) on rows
from
[Adventure Works]
Descendants with after
select
[Measures].[Internet Sales Amount]on columns,
descendants([Customer].[Customer Geography].[Country].[France],[Customer].[Customer Geography].[City],after)on rows
from
[Adventure Works] 

Descendants with before 
select
[Measures].[Internet Sales Amount]on columns,
descendants([Customer].[Customer Geography].[Country].[France],[Customer].[Customer Geography].[City],before) on rows
from [Adventure Works]

Range Function 
select
[Date].[Calendar].[Calendar Quarter].[Q1 CY 2003]:
[Date].[Calendar].[Calendar Quarter].[Q3 CY 2003]
on columns,[Measures].[Reseller Sales Amount]on rows
from [Adventure Works] 

Head(Top) Function 
select
{[Measures].[Internet Sales Amount],[Measures].[Internet Tax Amount]}
on columns,head([Customer].[Customer Geography].[Country],2)
on rows from [Adventure Works] 
--It will display first 2 countries from the dimension

Tail(Bottom) Function 
select
{[Measures].[Internet Sales Amount],[Measures].[Internet Tax Amount]}
on columns,tail([Customer].[Customer Geography].[Country],3)
on rows from [Adventure Works]
--it will show last three members of the Country level.

SSAS MDX Queries part 1

Simple MDX query 

SELECT [Measures].[Reseller Sales Amount] ON COLUMNS,
[Product].[Category].MEMBERS ON ROWS
FROM [Adventure Works]


Hiding Nulls
select non empty {[Date].[Calendar].[Calendar Year],[Date].[Calendar]}
on columns,
{[Product].[Product Categories].[Category],[Product].[Product Categories]}
on rows 
from [Adventure Works]

Introducing .members
select
{[Product].[Category].[Category].members,[Product].[Category].[All Products]} on columns,
[Measures].[Sales Amount] ON ROWS
from
[Adventure Works]

Individual Members
select
[Product].[Category].[Category].[Bikes] on columns,
[Measures].[Sales Amount] ON ROWS
from [Adventure Works]

Multiple Members
select
{[Product].[Category].[Bikes],[Product].[Category].[Clothing]} on columns ,
[Measures].[Sales Amount] ON ROWS
from [Adventure Works]

User Hierarchies
User hierarchies are created when dimensions are designed in BIDS. A user hierarchy is a
hierarchy that has three or more levels (including the All level at the top).

select
{[Product].[Product Categories].Allmembers}on columns
,{[Product].[Category].Allmembers} ON ROWS
from
[Adventure Works]WHERE [Measures].[Sales Amount]

Same Non-measure Dimension on Two Axes with Differing Hierarchies
select
[Date].[Calendar].[Calendar Year] on columns,
[Date].[Month of Year].[Month of Year] on rows
from [Adventure Works]

Cross Joins
If you crossjoin two sets of members from
the same dimension, the two sets must be based on different hierarchies within the
same dimension. You can even crossjoin two different dimension

Example 1 :
select
NONEMPTY({[Product].[Product Categories].Allmembers})on columns,
NONEMPTY(crossjoin([Date].[Calendar].[Calendar Year], [Date].[Month of Year].[Month of Year])) on rows
from
[Adventure Works] WHERE [Measures].[Internet Sales Amount]

Example 2:
select
{[Measures].[Internet Sales Amount],[Measures].[Reseller Sales Amount]} on columns,
crossjoin([Date].[Calendar].[Calendar Year],[Date].[Month of Year].[Month of Year]) on rows
from [Adventure Works]

Example 3:

select
crossjoin([Product].[Product Categories].[Category],{[Measures].[Internet Sales Amount],[Measures].[Reseller Sales Amount]}) on columns,
crossjoin([Date].[Calendar].[Calendar Year],[Date].[Month of Year].[Month of Year]) on rows
from
[Adventure Works]

Example 4(Crossjoin on Two Separate Non-measure Dimensions)

select
crossjoin([Sales Territory].[Sales Territory].[Country],[Product].[Product Categories].[Category]) on columns,
crossjoin([Date].[Calendar].[Calendar Year],[Date].[Month of Year].[Month of Year]) on rows
from
[Adventure Works]

Example 5:(Nested Cross Jons)
select
crossjoin([Sales Territory].[Sales Territory].[Country],crossjoin([Product].[Product Categories].[Category],
{[Measures].[Internet Order Count],[Measures].[Reseller Order Count]})) on columns,
crossjoin([Date].[Calendar].[Calendar Year],[Date].[Month of Year].[Month of Year]) on rows
from
[Adventure Works]


Alternate for Cross Joins
select
crossjoin([Sales Territory].[Sales Territory].[Country],[Product].[Product Categories].[Category],
{[Measures].[Internet Order Count],[Measures].[Reseller Order Count]})on columns,
([Date].[Calendar].[Calendar Year],[Date].[Month of Year].[Month of Year])on rows
from
[Adventure Works]

Friday, 19 August 2011

Built-in Functions - Cursor Functions

A cursor allows looping through a record set and performing a certain operation on each record within the set. SQL Server supports three functions that can help you while working with cursors: @@FETCH_STATUS, @@CURSOR_ROWS and CURSOR_STATUS. Cursor functions are non-deterministic.
A cursor life cycle can be described as follows:
  • Cursor is declared using the DECLARE CURSOR statement. This statement creates a cursor within SQL Server memory
  • Cursor is activated using OPEN CURSOR statement. At this point you can populate the cursor with a record set.
  • Data is retrieved from the cursor using the FETCH keyword.
  • A WHILE loop is executed within the cursor to perform some operation with the rows in the cursor with the condition that the FETCH command is successful.
  • Cursor is deactivated using CLOSE CURSOR statement. At this point you can't populate the cursor with additional rows. Nor can you work with rows within the cursor. However, you can re-open the cursor with OPEN CURSOR statement and perform additional work with the cursor.
  • The cursor is destroyed using DEALLOCATE CURSOR statement. Once the cursor is de-allocated it cannot be reopened.

@@FETCH

The most commonly used cursor function is @@FETCH_STATUS. This function determines whether FETCH keyword has successfully retrieved a row from the current cursor.
@@FETCH_STATUS can take one of the three values:
@@FETCH_STATUS valueMeaning
0Successful fetch of a row within a cursor
-1Fetch has failed. This could mean that the cursor has reached the beginning (or end) of the record set. This could also mean that we attempted retrieving a record that does not exist. For instance, if you attempt to grab 51st record within a cursor that has 50 records fetch status will be 1.
-2The fetched row is missing. This means the record you're trying to FETCH has been deleted or its key has been updated since you have opened the cursor.
For example, the following cursor is populated with the top 5 customer names. While the cursor fetches rows successfully the @@FETCH_STATUS is 0. Once we get to the end of the result set @@FETCH_STATUS becomes -1:
01.DECLARE @customer_full_name VARCHAR(85)
02.DECLARE customer_cursor CURSOR FOR  SELECT TOP 5 FirstName + ' ' + MiddleName + ' ' + LastName FROM dimCustomer 
03.OPEN customer_cursor 
04.FETCH NEXT FROM customer_cursor INTO @customer_full_name
05.WHILE @@FETCH_STATUS =
06.BEGIN   -- typically you'd do some row-based operation here 
07.FETCH NEXT FROM customer_cursor INTO @customer_full_name 
08.SELECT @@FETCH_STATUS AS fetch_status 
09.END 
10.CLOSE customer_cursor 
11.DEALLOCATE customer_cursor
Results:
01.fetch_status 
02.------------ 
03.0
04.fetch_status 
05.------------ 
06.0
07.fetch_status 
08.------------ 
09.0
10.fetch_status 
11.------------ 
12.0
13.fetch_status 
14.------------ 
15.-1

@@CURSOR_ROWS

@@CURSOR_ROWS function returns the number of rows in the cursor which was opened last on the current connection. This means that if you have 3 cursors open @@CURSOR_ROWS will return the number of rows in the 3rd cursor. @@CURSOR_ROWS can take the following values:
@@CURSOR_ROWS valueMeaning
-mCursor is being populated asynchronously. "M" is the value of records in the record set.
-1The cursor is DYNAMIC; that means, it reflects the changes to the data within the cursor. Therefore the number of rows can change due to addition or deletion of rows in the underlying tables. DYNAMIC cursors always return 1 as value of @@CURSOR_ROWS.
0 This can mean one of the following:
  • Cursor has not been opened
  • Cursor has no rows
  • Cursor has been closed
NNumber of rows in the cursor record set. N is reported after the cursor has been fully populated
The following example shows you how @@CURSOR_ROWS value changes during the lifetime of the cursor:
01.DECLARE  @last_name  VARCHAR(20),
02.@first_name VARCHAR(20)
03. 
04.DECLARE MY_CURSOR CURSOR  FOR
05.SELECT TOP 3 LASTNAME,
06.FIRSTNAME
07.FROM   DIMCUSTOMER
08. 
09.SELECT 'cursor has ' + CAST(@@CURSOR_ROWS AS VARCHAR) + ' rows'
10. 
11.OPEN MY_CURSOR
12. 
13.FETCH NEXT FROM MY_CURSOR
14.INTO @last_name,
15.@first_name
16. 
17.SELECT 'cursor has ' + CAST(@@CURSOR_ROWS AS VARCHAR) + ' rows'
18. 
19.WHILE @@FETCH_STATUS = 0
20.BEGIN-- typically you'd do some row-based operation here 
21.FETCH NEXT FROM MY_CURSOR
22.INTO @last_name,
23.@first_name
24.END
25. 
26.CLOSE MY_CURSOR
27. 
28.SELECT 'cursor has ' + CAST(@@CURSOR_ROWS AS VARCHAR) + ' rows'
29. 
30.DEALLOCATE MY_CURSOR
Results:
1.---------------------------------------------- 
2.cursor has 0 rows 
3.---------------------------------------------- 
4.cursor has 3 rows 
5.---------------------------------------------- 
6.cursor has 0 rows
If the same cursor is executed with DYNAMIC keyword against the entire DimCustomer table within Adventure Works database the results would show "cursor has -1 rows" while the cursor was being searched.

CURSOR_STATUS

The CURSOR_STATUS function can be used effectively within a stored procedure that calls another stored procedure, which returns an output parameter of CURSOR data type. This function can be used with local or global cursors and determines whether or not the stored procedure has returned a cursor with a result set. The syntax is:
1.CURSOR_STATUS( 'local' or 'global', cursor name)
or
1.CURSOR_STATUS ('variable', cursor variable name)
LOCAL or GLOBAL keywords allow you to specify the cursor scope; VARIABLE keyword specifies that CURSOR_STATUS function should examine a cursor variable.
In order to use the CURSOR data type as an output parameter, you must specify VARYING keyword along with OUTPUT within the CREATE PROCEDURE statement. The following example creates a procedure that returns a cursor as an output parameter:
01.CREATE PROCEDURE RETURN_CUSTOMER_NAMES(
02.@last_name VARCHAR(50),
03.@my_cursor CURSOR VARYING OUTPUT)
04.AS
05.BEGIN
06.SET NOCOUNT ON
07. 
08.SET @my_cursor =   CURSOR STATIC FOR   SELECT LastName, FirstName FROM DimCustomerWHERE LastName = @last_name
09. 
10.OPEN @my_cursor
11.END
Next, you can call this procedure from another procedure with a particular last name. The CURSOR_STATUS function will let you determine whether the cursor returned from the first procedure contains any rows, as follows:
01.CREATE PROCEDURE CALL_THE_OTHER_PROCEDURE
02.@last_name VARCHAR(50)
03.AS
04.SET NOCOUNT ON
05. 
06.DECLARE  @first_name VARCHAR(20)
07. 
08.DECLARE  @my_cursor CURSOR
09. 
10./* now call the procedure returning a cursor output parameter */
11.EXECUTE RETURN_CUSTOMER_NAMES
12.@last_name ,
13.@my_cursor OUTPUT
14. 
15.IF CURSOR_STATUS('variable','@my_cursor') = 0
16.BEGIN
17.PRINT 'no records found'
18. 
19.RETURN
20.END
21.ELSE
22.BEGIN
23.FETCH NEXT FROM @my_cursor
24.INTO @last_name,
25.@first_name
26. 
27.WHILE @@FETCH_STATUS = 0
28.BEGIN
29.SELECT @last_name,
30.@first_name
31. 
32.FETCH NEXT FROM @my_cursor
33.INTO @last_name,
34.@first_name
35.END
36. 
37.CLOSE @my_cursor
38. 
39.DEALLOCATE @my_cursor
40.END
Once the two procedures are created you can execute the caller procedure with the last name "Huang" as follows:
1.EXECUTE call_the_other_procedure 'huang'
Results (abbreviated):
1.-------------------------------------------------- -------------------- 
2.Huang  Eugene 
3.-------------------------------------------------- -------------------- 
4.Huang  Erica 
5.-------------------------------------------------- -------------------- 
6.Huang  Alejandro 
7.-------------------------------------------------- -------------------- 
8.Huang  Shannon
The following table summarizes the values returned by CURSOR_STATUS function:
CURSOR_STATUS valueMeaning for variableMeaning for cursor name
1 Cursor is open and has at least 1 row
DYNAMIC cursors return 1 even if they contain no rows
Cursor is open and has at least 1 row


DYNAMIC cursors return 1 even if they contain no rows
0Cursor is open but has no rowsCursor has no rows
-1The cursor is closed The cursor is closed
-2Cursor wasn't returned by the called procedure OR the cursor was deallocated prior to being assigned to this variableThe value of 2 is never returned by CURSOR_STATUS if you refer to cursor name
-3Cursor variable with the specified name does not exist OR the variable exists, but it hasn't been assigned to a cursor returned from the called procedureCursor with the specified name does not exist
The following example shows how the values returned by the CURSOR_STATUS function change during the cursor's lifecycle:
01.SET NOCOUNT ON 
02. 
03.SELECT 'cursor hasn''t been declared; the status is: ' + CAST(CURSOR_STATUS('global','my_cursor') AS VARCHAR)
04. 
05.DECLARE  @last_name  VARCHAR(20),
06.@first_name VARCHAR(20)
07. 
08.DECLARE MY_CURSOR CURSOR GLOBAL FOR
09.SELECT LASTNAME,
10.FIRSTNAME
11.FROM   DIMCUSTOMER
12.WHERE  LASTNAME = 'white'
13. 
14.SELECT 'cursor is declared; the status is: ' + CAST(CURSOR_STATUS('global','my_cursor') AS VARCHAR)
15. 
16.OPEN MY_CURSOR
17. 
18.SELECT 'cursor is opened; the status is: ' + CAST(CURSOR_STATUS('global','my_cursor') AS VARCHAR)
19. 
20.FETCH NEXT FROM MY_CURSOR
21.INTO @last_name,
22.@first_name
23. 
24.WHILE @@FETCH_STATUS = 0
25.BEGIN
26.SELECT @last_name,
27.@first_name
28. 
29.FETCH NEXT FROM MY_CURSOR
30.INTO @last_name,
31.@first_name
32.END
33. 
34.CLOSE MY_CURSOR
35. 
36.SELECT 'cursor is closed; the status is: ' + CAST(CURSOR_STATUS('global','my_cursor') AS VARCHAR)
37. 
38.DEALLOCATE MY_CURSOR
39. 
40.SELECT 'cursor is deallocated; the status is: ' + CAST(CURSOR_STATUS('global','my_cursor') AS VARCHAR)
Results (abbreviated):
01.-------------------------------------------------------------------------- 
02.cursor hasn't been declared; the status is: -
03.----------------------------------------------------------------- 
04.cursor is declared; the status is: -
05.--------------------------------------------------------------- 
06.cursor is opened; the status is: 1
07.-------------------- -------------------- 
08.WhiteIan 
09.--------------------------------------------------------------- 
10.cursor is closed; the status is: -
11.-------------------------------------------------------------------- 
12.cursor is deallocated; the status is: -3

Built-in Functions - String Functions

LEFT Function

Transact-SQL supports retrieving portions of the string. For instance, to retrieve the first few characters from the left of the string you use the LEFT function. The following example retrieves first four letters of employee last names in the AdventureWorksDW database:
1.SELECT LEFT(LastName, 4) AS FirstFourLettersOfLastName,  LastName FROM dbo.DimEmployee
Results (abbreviated):
1.FirstFourLettersOfLastName 
2.Gilb 
3.Brow 
4.Tamb 
5.Walt 
6.Walt

RIGHT Function

The RIGHT function retrieves the portion of the string counting from the right. For example:
1.SELECT RIGHT(LastName, 4) AS FirstFourLettersOfLastName,  LastName as FullLastName FROM dbo.DimEmployee
Results:
1.LastFourLettersOfLastName FullLastName 
2.bert Gilbert 
3.rown Brown 
4.ello Tamburello 
5.ters Walters 
6.ters Walters

LTRIM and RTRIM Functions

Notice that RIGHT and LEFT functions don't check for blank characters. In other words if your string contains a couple of leading blanks then LEFT(string_variable, 2) will return you two blank spaces, which might not be exactly what you want. If your data needs to be left aligned you can use LTRIM function, which removes the leading blanks. Similarly the RTRIM function removes the trailing characters. For instance, the following UPDATE statement will left align (remove any number of leading blanks) last names:
1.UPDATE DimEmployee SET LastName = LTRIM(LastName)
Similarly, if your data is padded with spaces and you don't wish to see spaces in your output you can use the RTRIM function. You could combine the two functions to remove both leading and trailing spaces as follows:
1.UPDATE DimEmployee SET LastName = LTRIM(RTRIM(LastName))

SUBSTRING Function

SUBSTRING function retrieves a portion of the string starting at the specified character and bringing back the number of characters specified; the syntax is:
1.SUBSTRING(string, starting_character_number, number_of_characters_to_return)
The following example will retrieve four characters from the employee last names, starting at the third character:
1.SELECT SUBSTRING(LastName, 3, 4) AS PortionOfLastName FROM DimEmployee
Results:
1.PortionOfLastName FullLastName 
2.lber Gilbert 
3.mbur Tamburello 
4.lter Walters 
5.lter Walters
Notice that the SUBSTRING function finds the starting character by counting from the left. In other words, if we run SUBSTRING(LastName, 3, 4) against the last name of "Buchanan" we start on the 3rd character from the left - "c".

REVERSE Function

The REVERSE function gives you a mirror image of a given string. The following example returns the mirror image of employee last names:
1.SELECT  REVERSE(LastName) AS MirrorImage,  LastName AS FullLastName  FROM DimEmployee
Results:
1.MirrorImage FullLastName 
2.trebliG Gilbert 
3.nworB Brown 
4.ollerubmaT Tamburello 
5.sretlaW Walters 
6.sretlaW Walters

CHARINDEX and PATINDEX Function

Transact-SQL supports two functions for finding an occurrence of a particular character (or number of characters) within a string: CHARINDEX and PATINDEX. CHARINDEX finds the starting position of a single character or string within a given column (or variable). In addition, if you suspect that the value you are searching for might occur multiple times within a given string you can specify the character number at which you want to start searching. The syntax of the function is:
1.CHARINDEX(search value, string, starting search location)
For example, you might wish to find a position of an apostrophe inside employee last names. The following query shows how this can be achieved using CHARINDEX function:
1.SELECT  CHARINDEX('''', LastName) AS ApostrophePosition,  LastName AS FullLastName  
2.FROM DimEmployee  WHERE lastname LIKE '%''%'
Results:
1.ApostrophePosition FullLastName 
2.2 D'Hers 
3.2 D'sa
Perhaps a more interesting example is finding an occurrence of a string, as opposed to an occurrence of a character. For example, city names often end with "ville", as in Huntsville or Clarksville. The following query finds the starting position of "ville" within city names:
1.SELECT  CHARINDEX('ville', city) AS Position,  City    FROM dimGeography  WHERE city LIKE '%ville'
Results:
1.Position City 
2.5 Daleville 
3.10 Campbellsville 
4.4 Melville 
5.6 Crossville 
6.5 Maryville
The next example finds the occurrence of the value within a variable, starting search at the 20th character:
1.DECLARE @variable VARCHAR(255) 
2.SELECT @variable = 'this is a string. this is also a string' 
3.SELECT  CHARINDEX('string', @variable, 20) AS Position
Results:
1.Position 
2.----------- 
3.34
PATINDEX function is very similar to CHARINDEX - it also finds the position of the first occurrence of a character or multiple characters. The difference is that you have to append % wildcards to PATINDEX; this function searches for a pattern. If you use a % wildcard with CHARINDEX you won't find anything, unless your data contains percent signs. If you're searching for a pattern at the end of the string expression, then you only have to use the % wildcard at the beginning of the pattern to be found, as in PATINDEX ('%pattern_to_find', string). The following query returns the same results as CHARINDEX example:
1.SELECT  PATINDEX('%ville%', city) AS Position,  City FROM dimGeography  WHERE city LIKE '%ville%'

REPLACE Function

REPLACE function replaces some characters within a string with another set of characters. The syntax is:
1.REPLACE(string expression, value to be replaced, replacing value)
For example, the following query replaces each occurrence of the word "payable" with "receivable":
1.SELECT AccountDescription,  REPLACE(AccountDescription, 'payable', 'receivable') AS DreamOn  
2.FROM dimAccount  WHERE AccountDescription LIKE '%payable%'

STUFF Function

The STUFF function inserts a set of characters into a given string at a given position. The syntax is:
1.STUFF(string to manipulate, starting position, length, characters to insert)
For example, the following query adds " town " string to every city in DimGeography table:
1.SELECT  STUFF(city, 5, 6, ' town ') AS Manipulated,  City  FROM dimGeography
Results:
1.Manipulated City 
2.Rock town n Rockhampton 
3.Town town  Townsville 
4.Clov town  Cloverdale 
5.Find town  Findon 
6.Pert town  Perth
You saw how to find the position of a specific character or number of characters using CHARINDEX. Now you can apply that knowledge and use STUFF function to replace characters based on their position.
The following example determines the position of 'ville' in the City column and then replaces it with 'town':
1.SELECT STUFF(city, CHARINDEX('ville', city), 6, ' town ') AS Manipulated,  City
2.FROM dimGeography  WHERE city LIKE '%ville'
Results:
1.Manipulated City 
2.Campbells town  Campbellsville 
3.Mel town  Melville 
4.Cross town  Crossville 
5.Mary town  Maryville 
6.Nash town  Nashville

LEN Function

The LEN function finds the length of the character string. The function takes the string as a single argument. For example, the following query shows the length of each city name:
1.SELECT  LEN(city) AS number_of_characters,  City  FROM dimGeography
Results:
1.Number_of_characters City 
2.10 Alexandria 
3.13 Coffs Harbour 
4.12 Darlinghurst 
5.8 Goulburn 
6.9 Lane Cove
  • Note: use the DATALENGTH system function to determine the number of characters in a TEXT column

REPLICATE Function

The REPLICATE function repeats a given string specified number of times. The syntax is: REPLICATE(string, number of times). For example, the following query prints the string '100' five times:
1.SELECT REPLICATE('100', 5)
Result:
1.100100100100100
One common usage of REPLICATE function is to combine it with other string functions and replace leading or trailing spaces with another character.
1.DECLARE @StringWithLeadingSpaces VARCHAR(10)   
2.SELECT @StringWithLeadingSpaces= '     SD3L6AA'   
3.SELECT @StringWithLeadingSpaces =  REPLICATE('0', LEN(@StringWithLeadingSpaces)
4.- LEN(LTRIM(@StringWithLeadingSpaces)))  + LTRIM(@StringWithLeadingSpaces) 
5.SELECT @StringWithLeadingSpaces AS StringWithOUTLeadingSpaces
Result:
1.StringWithOUTLeadingSpaces 
2.-------------------------- 
3.00000SD3L6

SPACE Function

The SPACE function is an equivalent of using REPLICATE to repeat spaces. This function takes a single argument - number of spaces you want to print.

UPPER and LOWER Functions

UPPER and LOWER functions change the case of the query's output. Both functions accept a string expression as the only argument. For example, the following query will return the US cities and corresponding states in mixed case:
1.SELECT UPPER(LEFT(City, 1)) +  LOWER(SUBSTRING(City, 2, (LEN(City) - 1))) + ',' + SPACE(2)
2.+ UPPER(LEFT(StateProvinceName, 1)) +  LOWER(SUBSTRING(StateProvinceName, 2,
3.(LEN(StateProvinceName) - 1)))  AS CityAndState
4.FROM DimGeography  WHERE CountryRegionCode = 'us'
Results (abbreviated):

1.CityAndState 
2.Chandler,  Arizona 
3.Gilbert,  Arizona 
4.Mesa,  Arizona 
5.Phoenix,  Arizona 
6.Scottsdale,  Arizona

ASCII Function

ASCII function returns the ASCII code value of the leftmost character of a string. This function is commonly used for comparing characters without knowing whether they're in upper or lower case. Upper case and lower case letters translate into different ASCII values, as the following example shows:
1.SELECT ASCII('A') AS UpperCase, ASCII('a') AS LowerCase
Results:
1.UpperCase   LowerCase 
2.----------- ----------- 
3.65          97

UNICODE Function

UNICODE function works just like ASCII, except it accepts the Unicode character value as input. This could be useful if you're working with international character sets.

CHAR Function

The CHAR function does the opposite of ASCII - it returns an alphanumeric equivalent of an ASCII code. CHAR function accepts a single argument - a number between 0 and 255. It is often necessary to append a carriage return, line feed, or both to the query output. In such cases you can effectively use CHAR function, as follows:
1.SELECT   'My Output'   + --Add three carriage returns and a line feed:
2.REPLICATE(CHAR(10), 3) + CHAR(13)  + 'AnotherOutput'
Results:
1.------------------------ 
2.My Output       
3.AnotherOutput

NCHAR Function

NCHAR function works exactly like CHAR except it returns the Unicode character. This function is useful if you're working with large international character sets. Unlike CHAR function NCHAR can handle values between 0 and 65535.

QUOTENAME Function

The QUOTENAME function appends square brackets to the beginning and end of the string expression and thereby makes a string expression a valid SQL Server identifier. QUOTENAME function is useful when working with database object names that contain spaces and reserved words. Generally it's a bad idea to use reserved words, special characters and spaces inside your object names. However at times, such as when working with 3rd party software, you do not have a choice. The following example uses QUOTENAME function to create a valid identifier:
1.SELECT QUOTENAME('column name with spaces')
Results:
1.[column name with spaces]

STR Function

The STR function converts a numeric value into a string. This function can be considered as a special case of CAST or CONVERT functions, both of which let you convert the variable from one data type into another compatible datatype. The STR function allows specifying the length of the string variable returned, as well as how many decimal points to include in the output. The syntax is:
1.STR(numeric value, length, decimal)
The length argument specifies the total length of the string. For example, '2.4503' consists of 6 characters. The decimal argument specifies how many characters are allowed to the right of the decimal point. For example, the following query returns a rounded currency rate as a string; the string has a total of six characters, five of which could be to the right of the decimal point:
1.SELECT  EndOfDayRate,  STR(EndOfDayRate, 6, 4) AS string_value
2.FROM factCurrencyRate  WHERE CurrencyKey = 3 AND timeKey = 2
Results:
1.EndOfDayRate string_value 
2.1.000900811 1.0009

SOUNDEX and DIFFERENCE Functions

The other two string functions available in SQL Server are SOUNDEX and DIFFERENCE, which happen to be rather similar and very seldom used. SOUNDEX provides a four character representation of the string (SOUNDEX code) and is supposed to help you determine whether two strings sound alike. For example, the following query retrieves SOUNDEX values for a few employees:
1.SELECT  SOUNDEX(LastName) AS soundex_code,  LastName  FROM DimEmployee
Results:

1.soundex_code string_value 
2.S650 Sharma 
3.S100 Shoop 
4.S150 Spoon 
5.S520 Song 
6.S520 Singh 
7.S550 Simon 
8.S530 Smith
The DIFFERENCE function provides a degree of similarity (or lack thereof) between the two character expressions. If the SOUNDEX values are the same for the two strings passed to the DIFFERENCE function then the degree of similarity is the highest - 4. Otherwise, the DIFFERENCE function will return 3, 2, 1 or 0. The DIFFERENCE function could be used when you wish to find all customers with a name that sounds similar to a known value, as in the following example:
1.SELECT LastName FROM DimEmployee WHERE DIFFERENCE (LastName, 'que') > 2
Results:
01.LastName 
02.Mu 
03.Liu 
04.Wu 
05.Liu 
06.Poe 
07.Li 
08.Loh 
09.Nay