SQL

SQL Server Strings

Strings:

String functionexampleAnswerDescription
AsciiSelect Ascii(‘A’)65Ascii of capital A
AsciiSelect Ascii(‘a’)97Ascii of small a
charSelect Char(65)AAlphabet of Ascii 65
charSelect Char(97)aAlphabet of Ascii 97
charindexSelect CHARINDEX(‘i’,’String’)4Position of the search string
charindexSelect CHARINDEX(‘i’,’Stringi’,5)7Position of the search string starting from 5th position
concatSelect Concat (‘SQL’,’String’)SQLStringCombines strings
datalengthSelect Datalength(‘ABC ‘)5Trailing spaces are included
datalengthSelect Datalength (‘ ABC’)5Leading spaces are included
datalengthSelect Datalength (‘AB C’)5Spaces in the string are included
formatSelect Format(1234567890,’###-###-####’)123-456-7890Formats the value
leftSelect Left(‘String’,3)StrExtracts the left 3 characters
lenSelect Len(‘ABC ‘)3Trailing spaces are ignored
lenSelect Len(‘ ABC’)5Leading spaces are included
lenSelect Len(‘AB C’)5Spaces in the string are included
ltrimSELECT LTRIM(‘ String’)StringTrims spaces on the left
patindexSELECT PATINDEX(‘%[0-9]%’,’SQL6 String’)4Returns the position of the first occurrence of pattern in a string. Wild cards can be used
quotenameSELECT QUOTENAME(‘ABCDEF’)[ABCDEF]Adds square brackets
replaceSELECT REPLACE(‘SQL replace example’,’ ‘,’*’)SQL*replace*exampleReplaces all occurrences of a string with another
replicateSELECT REPLICATE(‘P’,3)PPPReplicates the string specified number of times
reverseSELECT REVERSE(‘ABC’)CBAReverses a string
rtrimSELECT RTRIM(‘String ‘)StringTrims spaces on the right
string_splitSELECT VALUE FROM STRING_SPLIT(‘THIS,IS,SQL,String’,’,’)THIS
IS
SQL
String
Splits values separated by delimiter to columns. In this case the delimiter is comma
stuffSELECT STUFF(‘SQLString’,4,3,’*’)SQL*ingReplace part of a string with another. In this case starting from 4th character, 3 characters are replaced by *
substringSELECT Substring(‘Sql String’,5,3)StrExtract part of string. In this case part of string is extracted starting from 5th position, 3 characters
trimSELECT TRIM(‘ String ‘)StringTrim spaces both on left and right side of string