SQL - STRING - FUNCTIONS - 2
SQL - STRING - FUNCTIONS - 2
--Write a SQL Statement to get LastName from UserName with RIGHT function
--Note: Total Number of characters from UserName Minus SpacePisition from UserName is
Number Of Characters for LastName
SELECT
UserName,
LEN(UserName)-CHARINDEX(' ', UserName, 1) AS TotalLenMinusSpacePosition,
RIGHT(UserName, LEN(UserName)-CHARINDEX(' ', UserName, 1)) AS LastName
FROM Users
--Write a SQL Code To get FirstName and LastName from UserName with SUBSTRING()
SELECT
UserName,
SUBSTRING(UserName, 1, CHARINDEX(' ', UserName, 1)-1) AS FirstName,
SUBSTRING(UserName, CHARINDEX(' ', UserName, 1)+1, LEN(UserName)-CHARINDEX(' ',
UserName, 1)) AS LastName
FROM Users
/*
CONCATE_WS(delimiter/separator, text1, text2...): It is also used to concatenate two
or more strings with common delimiter
--Write a SQL Code to show FullName by concatenating FirstName and LastName
*/
USE ContosoRetailDW
SELECT
FirstName,
LastName,
CONCAT_WS('*', FirstName, LastName) AS FullName
FROM DimCustomer
--Write a SQL Code to get FullName by concatenationg FirstName, MiddleName and
LastName
SELECT
FirstName,
MiddleName,
LastName,
CONCAT_WS('*', FirstName, MiddleName, LastName) AS FullName
FROM DimCustomer
--Write a SQL Statement to get User Alias and User Domain from DimCustomer
SELECT
CustomerKey,
EmailAddress
FROM DimCustomer
/*
REPLACE(Text, FindText,ReplaceText): It is used to replace text with specified text
*/
--Write a SQL Statement to find number of characters from text without a characters
SELECT
UserName,
LEN(UserName) AS LenOfUserName,
LEN(REPLACE(UserName, 'a', '')) AS LenWithOuta,
LEN(UserName)-LEN(REPLACE(UserName, 'a', '')) AS TotalNoOfas
FROM Users
/*
TRIM(text): It is used to trim from starting of the text and ending of the text
LTRIM(text): It is used to trim from only starting of the text
RTRIM(text): It is used to trim from only ending of the text
*/
SELECT
empno,
ename,
LEN(ename) AS LenOfEname,
TRIM(ename) AS trim_ename,
LEN(TRIM(ename)) AS lenAfterTrim,
LTRIM(ename) AS ltrim_ename,
LEN(LTRIM(ename)) AS lenAfterLtrim,
RTRIM(ename) AS rtrim_ename,
LEN(RTRIM(ename)) AS lenAfterRtrim
FROM empdata