Splitting an SQL string into multiple strings - sql

I am trying to split a single string containing multiple email address data into three variables. The strings mark the start/end of an email address with the ; character.
An example string would be:
'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com'
The code I currently have for this is as follows:
DECLARE #Email VARCHAR(100),
#Email2 VARCHAR(100),
#Email3 VARCHAR(100)
SET #Email = 'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com'
SET #Email2 = SUBSTRING(#Email, CHARINDEX(';', #Email)+1, LEN(#Email))
SET #Email3 = SUBSTRING(#Email, CHARINDEX(';', #Email)+1, LEN(#Email))
SET #Email = SUBSTRING(#Email, 1, CHARINDEX(';', #Email)-1)
Unfortunately this doesn't seem to work. Could someone please point out where I am going wrong and what I should do to fix my problem?
Thanks in advance.

Assuming that there will always be 3 email addresses - the following seems to work;
DECLARE #Email VARCHAR(100),
#Email2 VARCHAR(100),
#Email3 VARCHAR(100)
SET #Email = 'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com'
SELECT #Email = LEFT(#Email, CHARINDEX(';', #Email) - 1)
,#Email2 = SUBSTRING (
#Email,
CHARINDEX(';', #Email) + 1,
CHARINDEX(';', #Email, CHARINDEX(';', #Email) + 1) - LEN(LEFT(#Email, CHARINDEX(';', #Email) )) - 1
)
,#Email3 = RIGHT(#Email, CHARINDEX(';', #Email)-1)

This solution:
create function dbo.SplitString
(
#str nvarchar(max),
#separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(#separator, #str)
union all
select
p + 1,
b + 1,
charindex(#separator, #str, b + 1)
from tokens
where b > 0
)
select
p-1 ItemIndex,
substring(
#str,
a,
case when b > 0 then b-a ELSE LEN(#str) end)
AS Item
from tokens
);
GO
Taken from How do I split a string so I can access item x

In SQL Server 2016 you can use the built-in STRING_SPLIT function.
SELECT value FROM STRING_SPLIT(#var, ';')

Try using XML nodes to split and parse your string. Code sample below:
declare #Email as varchar(100), #del as varchar(10), #xml as xml;
set #Email='joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com';
set #del =';';
set #xml = '<root><c>' + replace(#Email,#del,'</c><c>') + '</c></root>';
select email.value('.','varchar(100)') as Email
from #xml.nodes('//root/c') as records(email);

Here this works I came across it quite sometime ago. Cannot take any credit for the work but this will work perfectly.
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
select *from dbo.fnSplitString('joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com',';')

I wrote this function that I use on a regular basis...
CREATE FUNCTION func_split(#value VARCHAR(8000), #delim CHAR)
RETURNS
#outtable TABLE (
i INTEGER,
value VARCHAR(1024)
)
AS
BEGIN
DECLARE #pos INTEGER
DECLARE #count INTEGER
IF LEN(#value) > 0
BEGIN
SET #count = 1
SET #value = #value + #delim
SET #pos = CHARINDEX(#delim, #value, 1)
WHILE #pos > 0
BEGIN
INSERT INTO #outtable (i, value) VALUES (#count, LEFT(#value, #pos - 1))
SET #value = RIGHT(#value, LEN(#value) - #pos)
SET #pos = CHARINDEX(#delim, #value, 1)
SET #count = #count + 1
END
END
RETURN
END
You when then call it with...
DECLARE #emails AS TABLE (
i INTEGER,
value VARCHAR(1024)
)
INSERT INTO #split SEELCT * FROM func_split('joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com', ';');
...and you end up with a temp table full of email addresses, i being their input order.

Your best bet is to turn the delimited string into columnar form and work from there.
You can use the iterative method, or the method using the Numbers table (which I prefer):
declare
#list varchar(1000),
#sep char(1)
set #list = 'joebloggs#gmailcom;jimbowen#aol.com;dannybaker#msn.com';
set #sep = ';'
-- iterative method
declare #res table (
c varchar(100)
)
declare
#pos_start int,
#pos_end int,
#len_sep int,
#exit int
select #pos_start = 1, #pos_end = 1, #len_sep = len(#sep), #exit = 0
while #exit = 0
begin
set #pos_end = charindex(#sep, #list, #pos_start)
if #pos_end <= 0 begin
set #pos_end = len(#list) + 1
set #exit = 1
end
insert #res(c) select substring(#list, #pos_start, #pos_end - #pos_start)
set #pos_start = #pos_end + #len_sep
end
select * from #res
-- the Numbers table method
select substring(#list, n, charindex(#sep, #list + #sep, n) - n)
from numbers
where substring(#sep + #list, n, 1) = #sep
and n < len(#list) + 1

Related

SQL Server capitalize every first letter of every word with loop [duplicate]

What’s the best way to capitalize the first letter of each word in a string in SQL Server.
From http://www.sql-server-helper.com/functions/initcap.aspx
CREATE FUNCTION [dbo].[InitCap] ( #InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE #Index INT
DECLARE #Char CHAR(1)
DECLARE #PrevChar CHAR(1)
DECLARE #OutputString VARCHAR(255)
SET #OutputString = LOWER(#InputString)
SET #Index = 1
WHILE #Index <= LEN(#InputString)
BEGIN
SET #Char = SUBSTRING(#InputString, #Index, 1)
SET #PrevChar = CASE WHEN #Index = 1 THEN ' '
ELSE SUBSTRING(#InputString, #Index - 1, 1)
END
IF #PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
BEGIN
IF #PrevChar != '''' OR UPPER(#Char) != 'S'
SET #OutputString = STUFF(#OutputString, #Index, 1, UPPER(#Char))
END
SET #Index = #Index + 1
END
RETURN #OutputString
END
GO
There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."):
http://www.devx.com/tips/Tip/17608
As a table-valued function:
CREATE FUNCTION dbo.InitCap(#v AS VARCHAR(MAX))
RETURNS TABLE
AS
RETURN
WITH a AS (
SELECT (
SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()'
FROM string_split(#v, ' ')
ORDER BY CHARINDEX(value,#v)
FOR XML PATH (''), TYPE) ret)
SELECT CAST(a.ret AS varchar(MAX)) ret from a
GO
Note that string_split requires COMPATIBILITY_LEVEL 130.
A variation of the one I've been using for quite some time is:
CREATE FUNCTION [widget].[properCase](#string varchar(8000)) RETURNS varchar(8000) AS
BEGIN
SET #string = LOWER(#string)
DECLARE #i INT
SET #i = ASCII('a')
WHILE #i <= ASCII('z')
BEGIN
SET #string = REPLACE( #string, ' ' + CHAR(#i), ' ' + CHAR(#i-32))
SET #i = #i + 1
END
SET #string = CHAR(ASCII(LEFT(#string, 1))-32) + RIGHT(#string, LEN(#string)-1)
RETURN #string
END
You can easily modify to handle characters after items other than spaces if you wanted to.
Another solution without using the loop - pure set-based approach with recursive CTE
create function [dbo].InitCap (#value varchar(max))
returns varchar(max) as
begin
declare
#separator char(1) = ' ',
#result varchar(max) = '';
with r as (
select value, cast(null as varchar(max)) [x], cast('' as varchar(max)) [char], 0 [no] from (select rtrim(cast(#value as varchar(max))) [value]) as j
union all
select right(value, len(value)-case charindex(#separator, value) when 0 then len(value) else charindex(#separator, value) end) [value]
, left(r.[value], case charindex(#separator, r.value) when 0 then len(r.value) else abs(charindex(#separator, r.[value])-1) end ) [x]
, left(r.[value], 1)
, [no] + 1 [no]
from r where value > '')
select #result = #result +
case
when ascii([char]) between 97 and 122
then stuff(x, 1, 1, char(ascii([char])-32))
else x
end + #separator
from r where x is not null;
set #result = rtrim(#result);
return #result;
end
If you are looking for the answer to the same question in Oracle/PLSQL then you may use the function INITCAP. Below is an example for the attribute dname from a table department which has the values ('sales', 'management', 'production', 'development').
SQL> select INITCAP(dname) from department;
INITCAP(DNAME)
--------------------------------------------------
Sales
Management
Production
Development
;WITH StudentList(Name) AS (
SELECT CONVERT(varchar(50), 'Carl-VAN')
UNION SELECT 'Dean o''brian'
UNION SELECT 'Andrew-le-Smith'
UNION SELECT 'Eddy thompson'
UNION SELECT 'BOBs-your-Uncle'
), Student AS (
SELECT CONVERT(varchar(50), UPPER(LEFT(Name, 1)) + LOWER(SUBSTRING(Name, 2, LEN(Name)))) Name,
pos = PATINDEX('%[-'' ]%', Name)
FROM StudentList
UNION ALL
SELECT CONVERT(varchar(50), LEFT(Name, pos) + UPPER(SUBSTRING(Name, pos + 1, 1)) + SUBSTRING(Name, pos + 2, LEN(Name))) Name,
pos = CASE WHEN PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) = 0 THEN 0 ELSE pos + PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) END
FROM Student
WHERE pos > 0
)
SELECT Name
FROM Student
WHERE pos = 0
ORDER BY Name
This will result in:
Andrew-Le-Smith
Bobs-Your-Uncle
Carl-Van
Dean O'Brian
Eddy Thompson
Using a recursive CTE set based query should out perform a procedural while loop query.
Here I also have made my separate to be 3 different characters [-' ] instead of 1 for a more advanced example. Using PATINDEX as I have done allows me to look for many characters. You could also use CHARINDEX on a single character and this function excepts a third parameter StartFromPosition so I could further simply my 2nd part of the recursion of the pos formula to (assuming a space): pos = CHARINDEX(' ', Name, pos + 1).
The suggested function works fine, however, if you do not want to create any function this is how I do it:
select ID,Name
,string_agg(concat(upper(substring(value,1,1)),lower(substring(value,2,len(value)-1))),' ') as ModifiedName
from Table_Customer
cross apply String_Split(replace(trim(Name),' ',' '),' ')
where Name is not null
group by ID,Name;
The above query split the words by space (' ') and create different rows of each having one substring, then convert the first letter of each substring to upper and keep remaining as lower. The final step is to string aggregate based on the key.
BEGIN
DECLARE #string varchar(100) = 'asdsadsd asdad asd'
DECLARE #ResultString varchar(200) = ''
DECLARE #index int = 1
DECLARE #flag bit = 0
DECLARE #temp varchar(2) = ''
WHILE (#Index <LEN(#string)+1)
BEGIN
SET #temp = SUBSTRING(#string, #Index-1, 1)
--select #temp
IF #temp = ' ' OR #index = 1
BEGIN
SET #ResultString = #ResultString + UPPER(SUBSTRING(#string, #Index, 1))
END
ELSE
BEGIN
SET #ResultString = #ResultString + LOWER(SUBSTRING(#string, #Index, 1))
END
SET #Index = #Index+ 1--increase the index
END
SELECT #ResultString
END
It can be as simple as this:
DECLARE #Name VARCHAR(500) = 'Roger';
SELECT #Name AS Name, UPPER(LEFT(#Name, 1)) + SUBSTRING(#Name, 2, LEN(#Name)) AS CapitalizedName;
fname is column name if fname value is akhil then UPPER(left(fname,1)) provide capital First letter(A) and substring function SUBSTRING(fname,2,LEN(fname)) provide(khil) concate both using + then result is (Akhil)
select UPPER(left(fname,1))+SUBSTRING(fname,2,LEN(fname)) as fname
FROM [dbo].[akhil]
On SQL Server 2016+ using JSON which gives guaranteed order of the words:
CREATE FUNCTION [dbo].[InitCap](#Text NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN STUFF((
SELECT ' ' + UPPER(LEFT(s.value,1)) + LOWER(SUBSTRING(s.value,2,LEN(s.value)))
FROM OPENJSON('["' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(#Text,'\','\\'),'"','\"'),CHAR(9),'\t'),CHAR(10),'\n'),' ','","') + '"]') s
ORDER BY s.[key]
FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'');
END
GO
CREATE FUNCTION [dbo].[Capitalize](#text NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS
BEGIN
DECLARE #result NVARCHAR(MAX) = '';
DECLARE #c NVARCHAR(1);
DECLARE #i INT = 1;
DECLARE #isPrevSpace BIT = 1;
WHILE #i <= LEN(#text)
BEGIN
SET #c = SUBSTRING(#text, #i, 1);
SET #result += IIF(#isPrevSpace = 1, UPPER(#c), LOWER(#c));
SET #isPrevSpace = IIF(#c LIKE '[ -]', 1, 0);
SET #i += 1;
END
RETURN #result;
END
GO
DECLARE #sentence NVARCHAR(100) = N'i-thINK-this soLUTION-works-LiKe-a charm';
PRINT dbo.Capitalize(#sentence);
-- I-Think-This Solution-Works-Like-A Charm
Here is the simplest one-liner to do this:
SELECT LEFT(column, 1)+ lower(RIGHT(column, len(column)-1) ) FROM [tablename]
I was looking for the best way to capitalize and i recreate simple sql script
how to use SELECT dbo.Capitalyze('this is a test with multiple spaces')
result "This Is A Test With Multiple Spaces"
CREATE FUNCTION Capitalyze(#input varchar(100) )
returns varchar(100)
as
begin
declare #index int=0
declare #char as varchar(1)=' '
declare #prevCharIsSpace as bit=1
declare #Result as varchar(100)=''
set #input=UPPER(LEFT(#input,1))+LOWER(SUBSTRING(#input, 2, LEN(#input)))
set #index=PATINDEX('% _%',#input)
if #index=0
set #index=len(#input)
set #Result=substring(#input,0,#index+1)
WHILE (#index < len(#input))
BEGIN
SET #index = #index + 1
SET #char=substring(#input,#index,1)
if (#prevCharIsSpace=1)
begin
set #char=UPPER(#char)
if (#char=' ')
set #char=''
end
if (#char=' ')
set #prevCharIsSpace=1
else
set #prevCharIsSpace=0
set #Result=#Result+#char
--print #Result
END
--print #Result
return #Result
end
IF OBJECT_ID ('dbo.fnCapitalizeFirstLetterAndChangeDelimiter') IS NOT NULL
DROP FUNCTION dbo.fnCapitalizeFirstLetterAndChangeDelimiter
GO
CREATE FUNCTION [dbo].[fnCapitalizeFirstLetterAndChangeDelimiter] (#string NVARCHAR(MAX), #delimiter NCHAR(1), #new_delimeter NCHAR(1))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #result NVARCHAR(MAX)
SELECT #result = '';
IF (LEN(#string) > 0)
DECLARE #curr INT
DECLARE #next INT
BEGIN
SELECT #curr = 1
SELECT #next = CHARINDEX(#delimiter, #string)
WHILE (LEN(#string) > 0)
BEGIN
SELECT #result =
#result +
CASE WHEN LEN(#result) > 0 THEN #new_delimeter ELSE '' END +
UPPER(SUBSTRING(#string, #curr, 1)) +
CASE
WHEN #next <> 0
THEN LOWER(SUBSTRING(#string, #curr+1, #next-2))
ELSE LOWER(SUBSTRING(#string, #curr+1, LEN(#string)-#curr))
END
IF (#next > 0)
BEGIN
SELECT #string = SUBSTRING(#string, #next+1, LEN(#string)-#next)
SELECT #next = CHARINDEX(#delimiter, #string)
END
ELSE
SELECT #string = ''
END
END
RETURN #result
END
GO

Getting syntax error while using table variable in table value function in SQL Server 2012

I am trying to use table variable with table value function but I am getting a syntax error. Please help me to solve this.
Here is the code:
Create FUNCTION [dbo].[SplitStrings1]
(#List NVARCHAR(MAX),
#Delimiter NVARCHAR(255))
RETURNS #Results TABLE(Col1 int)
AS
BEGIN
declare #tblHelping table (Col1 int);
declare #i int
declare #rows_to_insert int
set #i = 1
set #rows_to_insert = 1000
while #i < #rows_to_insert
begin
INSERT INTO #tblHelping VALUES (#i)
set #i = #i + 1
end
(SELECT
Number = ROW_NUMBER() OVER (ORDER BY Number),
Item FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(#List, Number,
CHARINDEX(#Delimiter, #List + #Delimiter, Number) - Number)))
FROM
(SELECT * FROM #tblHelping) AS n(Number)
WHERE
Number <= CONVERT(INT, LEN(#List))
AND SUBSTRING(#Delimiter + #List, Number, 1) = #Delimiter) AS y)
END
I am getting this error
A RETURN statement with a return value cannot be used in this context.
If you want to use your function then working version below. But there is better solution, please see:
Split strings the right way – or the next best way as recomended by
#SeanLange
How to split string using delimiter char using T-SQL?
How do I split a string so I can access item x?
.
CREATE FUNCTION [dbo].[SplitStrings1]
( #List NVARCHAR(MAX)
, #Delimiter NVARCHAR(255))
RETURNS #Results TABLE
(Number INT, Item NVARCHAR(MAX) )
AS
BEGIN
declare #tblHelping table (Col1 int);
declare #i int
declare #rows_to_insert int
SET #i = 1
SET #rows_to_insert = 1000
while #i < #rows_to_insert
begin
INSERT INTO #tblHelping VALUES (#i)
set #i = #i + 1
end
insert into #Results
SELECT Number = ROW_NUMBER() OVER (ORDER BY Number)
, Item
FROM (SELECT Number
, Item = LTRIM(RTRIM(SUBSTRING(#List, Number,CHARINDEX(#Delimiter, #List + #Delimiter, Number) - Number)))
FROM (SELECT * FROM #tblHelping) AS n(Number)
WHERE Number <= CONVERT(INT, LEN(#List))
AND SUBSTRING(#Delimiter + #List, Number, 1) = #Delimiter) AS y
RETURN
END
Or try something like that:
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END

User Defined Function to get longest word in a string in SQL Server

I've trying to create a UDF in SQL to return the longest word in a string. I've created the following but I cant get it to work properly. Any suggestions?
CREATE FUNCTION [dbo].[ufn_Longestword] (#input varchar(255))
RETURNS varchar(100)
AS
BEGIN
declare #pos int
declare #pos2 int
declare #wordpos int
declare #longestword varchar(100)
declare #Letter1 varchar (1)
declare #Letter2 varchar (1)
declare #twords table (
words varchar(100))
SET #pos = 1
WHILE #pos <= len(#input)
BEGIN
SET #Letter1 = substring(#input, #pos, 1)
IF #Letter1 = ' '
BEGIN
SET #pos2 = #pos
WHILE #pos2 <= len(#input)
BEGIN
SET #Letter2 = substring(#input, #pos2, 1)
if #letter2 = ' '
BEGIN
insert into #twords
select SUBSTRING(#input, #pos,#pos2 - #pos)
END
SET #pos2 = #pos2 + 1
END
END
SET #pos = #pos + 1
END
SET #longestword = (select top 1 words from #twords
ORDER BY len(words)desc)
delete from #twords
RETURN #longestword
END
I#m trying to get the different between the 2 spaces and insert that word into a temp table but it doesnt work.
Instead you can use this.
DECLARE #str VARCHAR(5000)='aaaa bbbbb cccccccc'
SELECT TOP 1 Split.a.value('.', 'VARCHAR(100)') as longest_Word
FROM (SELECT Cast ('<M>' + Replace(#str, ' ', '</M><M>') + '</M>' AS XML) AS Data) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
ORDER BY Len(Split.a.value('.', 'VARCHAR(100)')) DESC
Result : cccccccc
i found this as solution :
click Here
CREATE FUNCTION FN_ex06(#str varchar(8000) )
RETURNS #T TABLE
( position int IDENTITY PRIMARY KEY,
value varchar(8000) ,
length smallint null
)
AS
BEGIN
DECLARE #i int
SET #i = -1
WHILE (LEN(#str) > 0)
BEGIN
SET #i = CHARINDEX(' ' , #str) /* here i used space as delimiter*/
IF (#i = 0) AND (LEN(#str) > 0)
BEGIN
INSERT INTO #T (value, length) VALUES (#str, LEN(#str))
BREAK
END
IF (#i > 1)
BEGIN
INSERT INTO #T (value, length) VALUES (LEFT(#str, #i - 1),
LEN(LEFT(#str, #i - 1)))
SET #str = RIGHT(#str, (LEN(#str) - #i))
END
ELSE
SET #str = RIGHT(#str, (LEN(#str) - #i))
END
RETURN
END
to run this function you treat it as table because return is a table
select max(value) from FN_ex06('karim pentester')
result is : pentester
of course you select all other columns in return table

SQL Server Equivalent to ORACLE INSTR

I wanted to know if in SQL Server there is an equivalent to the Oracle INSTR function?
I know that there is CHARINDEX and PATINDEX, but with the Oracle version I can also specify the Nth appearance of the character(s) I am looking for.
Oracle INSTR:
instr( string1, string2 [, start_position [, **nth_appearance** ] ] )
The CHARINDEX almost gets me there, but I wanted to have it start at the nth_appearance of the character in the string.
You were spot on that nth_appearance does not exist in SQL Server.
Shamelessly copying a function (Equivalent of Oracle's INSTR with 4 parameters in SQL Server) created for your problem (please note that #Occurs is not used the same way as in Oracle - you can't specify "3rd appearance", but "occurs 3 times"):
CREATE FUNCTION udf_Instr
(#str1 varchar(8000), #str2 varchar(1000), #start int, #Occurs int)
RETURNS int
AS
BEGIN
DECLARE #Found int, #LastPosition int
SET #Found = 0
SET #LastPosition = #start - 1
WHILE (#Found < #Occurs)
BEGIN
IF (CHARINDEX(#str1, #str2, #LastPosition + 1) = 0)
BREAK
ELSE
BEGIN
SET #LastPosition = CHARINDEX(#str1, #str2, #LastPosition + 1)
SET #Found = #Found + 1
END
END
RETURN #LastPosition
END
GO
SELECT dbo.udf_Instr('x','axbxcxdx',1,4)
GO
DROP FUNCTION udf_Instr
GO
Here is a version of Oracle's INSTR function which also works with a negative position for a reverse lookup as per Oracle's Doc here :- https://docs.oracle.com/cd/B28359_01/olap.111/b28126/dml_functions_1103.htm#OLADM564
CREATE FUNCTION dbo.INSTR(#str NVARCHAR(MAX), #substr NVARCHAR(MAX), #position INT = 1, #occurance INT = 1)
RETURNS INT
AS
BEGIN
DECLARE #loc INT = #position;
IF #loc < 0
BEGIN
SET #str = REVERSE(#str);
SET #substr = REVERSE(#substr);
SET #loc = #loc * -1;
END
IF #loc > 0
BEGIN
SET #loc = #loc - 1;
END
WHILE (#occurance > 0 AND CHARINDEX(#substr, #str, #loc + 1) > 0)
BEGIN
SET #loc = CHARINDEX(#substr, #str, #loc + 1);
SET #occurance = #occurance - 1;
END
IF #occurance > 0
BEGIN
SET #loc = 0;
END
IF #position < 0
BEGIN
SET #loc = LEN(#str) - #loc;
END
RETURN #loc
END
Change #str1 varchar(8000), #str2 varchar(1000) to #str1 varchar(1000), #str2 varchar(8000)
or
change CHARINDEX(#str1, #str2, #LastPosition + 1) to CHARINDEX(#str2, #str1, #LastPosition + 1)
You can use the following UDF (inline function rather than scalar)
CREATE FUNCTION dbo.INSTR
(
#str VARCHAR(8000),
#Substr VARCHAR(1000),
#start INT ,
#Occurance INT
)
RETURNS TABLE
AS
RETURN
WITH Tally (n) AS
(
SELECT TOP (LEN(#str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0)) a(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(n)
)
, Find_N_STR as
(
SELECT
CASE WHEN DENSE_RANK() OVER(PARTITION BY #Substr ORDER BY (CHARINDEX(#Substr ,#STR ,N))) = #Occurance
THEN MAX(N-#start +1) OVER (PARTITION BY CHARINDEX(#Substr ,#STR ,N) )
ELSE 0
END [Loc]
FROM Tally
WHERE CHARINDEX(#Substr ,#STR ,N) > 0
)
SELECT Loc= MAX(Loc)
FROM Find_N_STR
WHERE Loc > 0
How to use:
declare #T table
(
Name_Level_Class_Section varchar(25)
)
insert into #T values
('Jacky_1_B2_23'),
('Johnhy_1_B2_24'),
('Peter_2_A5_3')
select t.Name_Level_Class_Section , l.Loc
from #t t
cross apply dbo.INSTR (t.Name_Level_Class_Section, '_',1,2) l
Try this !!
CREATE FUNCTION dbo.INSTR (#str VARCHAR(8000), #substr VARCHAR(255), #start INT, #occurrence INT)
RETURNS INT
AS
BEGIN
DECLARE #found INT = #occurrence,
#pos INT = #start;
WHILE 1=1
BEGIN
-- Find the next occurrence
SET #pos = CHARINDEX(#substr, #str, #pos);
-- Nothing found
IF #pos IS NULL OR #pos = 0
RETURN #pos;
-- The required occurrence found
IF #found = 1
BREAK;
-- Prepare to find another one occurrence
SET #found = #found - 1;
SET #pos = #pos + 1;
END
RETURN #pos;
END
GO
Usage :
-- Find the second occurrence of letter 'o'
SELECT dbo.INSTR('Moscow', 'o', 1, 2);
-- Result: 5

How to capitalize the first letter of each word in a string in SQL Server

What’s the best way to capitalize the first letter of each word in a string in SQL Server.
From http://www.sql-server-helper.com/functions/initcap.aspx
CREATE FUNCTION [dbo].[InitCap] ( #InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE #Index INT
DECLARE #Char CHAR(1)
DECLARE #PrevChar CHAR(1)
DECLARE #OutputString VARCHAR(255)
SET #OutputString = LOWER(#InputString)
SET #Index = 1
WHILE #Index <= LEN(#InputString)
BEGIN
SET #Char = SUBSTRING(#InputString, #Index, 1)
SET #PrevChar = CASE WHEN #Index = 1 THEN ' '
ELSE SUBSTRING(#InputString, #Index - 1, 1)
END
IF #PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
BEGIN
IF #PrevChar != '''' OR UPPER(#Char) != 'S'
SET #OutputString = STUFF(#OutputString, #Index, 1, UPPER(#Char))
END
SET #Index = #Index + 1
END
RETURN #OutputString
END
GO
There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."):
http://www.devx.com/tips/Tip/17608
As a table-valued function:
CREATE FUNCTION dbo.InitCap(#v AS VARCHAR(MAX))
RETURNS TABLE
AS
RETURN
WITH a AS (
SELECT (
SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()'
FROM string_split(#v, ' ')
ORDER BY CHARINDEX(value,#v)
FOR XML PATH (''), TYPE) ret)
SELECT CAST(a.ret AS varchar(MAX)) ret from a
GO
Note that string_split requires COMPATIBILITY_LEVEL 130.
A variation of the one I've been using for quite some time is:
CREATE FUNCTION [widget].[properCase](#string varchar(8000)) RETURNS varchar(8000) AS
BEGIN
SET #string = LOWER(#string)
DECLARE #i INT
SET #i = ASCII('a')
WHILE #i <= ASCII('z')
BEGIN
SET #string = REPLACE( #string, ' ' + CHAR(#i), ' ' + CHAR(#i-32))
SET #i = #i + 1
END
SET #string = CHAR(ASCII(LEFT(#string, 1))-32) + RIGHT(#string, LEN(#string)-1)
RETURN #string
END
You can easily modify to handle characters after items other than spaces if you wanted to.
Another solution without using the loop - pure set-based approach with recursive CTE
create function [dbo].InitCap (#value varchar(max))
returns varchar(max) as
begin
declare
#separator char(1) = ' ',
#result varchar(max) = '';
with r as (
select value, cast(null as varchar(max)) [x], cast('' as varchar(max)) [char], 0 [no] from (select rtrim(cast(#value as varchar(max))) [value]) as j
union all
select right(value, len(value)-case charindex(#separator, value) when 0 then len(value) else charindex(#separator, value) end) [value]
, left(r.[value], case charindex(#separator, r.value) when 0 then len(r.value) else abs(charindex(#separator, r.[value])-1) end ) [x]
, left(r.[value], 1)
, [no] + 1 [no]
from r where value > '')
select #result = #result +
case
when ascii([char]) between 97 and 122
then stuff(x, 1, 1, char(ascii([char])-32))
else x
end + #separator
from r where x is not null;
set #result = rtrim(#result);
return #result;
end
If you are looking for the answer to the same question in Oracle/PLSQL then you may use the function INITCAP. Below is an example for the attribute dname from a table department which has the values ('sales', 'management', 'production', 'development').
SQL> select INITCAP(dname) from department;
INITCAP(DNAME)
--------------------------------------------------
Sales
Management
Production
Development
;WITH StudentList(Name) AS (
SELECT CONVERT(varchar(50), 'Carl-VAN')
UNION SELECT 'Dean o''brian'
UNION SELECT 'Andrew-le-Smith'
UNION SELECT 'Eddy thompson'
UNION SELECT 'BOBs-your-Uncle'
), Student AS (
SELECT CONVERT(varchar(50), UPPER(LEFT(Name, 1)) + LOWER(SUBSTRING(Name, 2, LEN(Name)))) Name,
pos = PATINDEX('%[-'' ]%', Name)
FROM StudentList
UNION ALL
SELECT CONVERT(varchar(50), LEFT(Name, pos) + UPPER(SUBSTRING(Name, pos + 1, 1)) + SUBSTRING(Name, pos + 2, LEN(Name))) Name,
pos = CASE WHEN PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) = 0 THEN 0 ELSE pos + PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) END
FROM Student
WHERE pos > 0
)
SELECT Name
FROM Student
WHERE pos = 0
ORDER BY Name
This will result in:
Andrew-Le-Smith
Bobs-Your-Uncle
Carl-Van
Dean O'Brian
Eddy Thompson
Using a recursive CTE set based query should out perform a procedural while loop query.
Here I also have made my separate to be 3 different characters [-' ] instead of 1 for a more advanced example. Using PATINDEX as I have done allows me to look for many characters. You could also use CHARINDEX on a single character and this function excepts a third parameter StartFromPosition so I could further simply my 2nd part of the recursion of the pos formula to (assuming a space): pos = CHARINDEX(' ', Name, pos + 1).
The suggested function works fine, however, if you do not want to create any function this is how I do it:
select ID,Name
,string_agg(concat(upper(substring(value,1,1)),lower(substring(value,2,len(value)-1))),' ') as ModifiedName
from Table_Customer
cross apply String_Split(replace(trim(Name),' ',' '),' ')
where Name is not null
group by ID,Name;
The above query split the words by space (' ') and create different rows of each having one substring, then convert the first letter of each substring to upper and keep remaining as lower. The final step is to string aggregate based on the key.
BEGIN
DECLARE #string varchar(100) = 'asdsadsd asdad asd'
DECLARE #ResultString varchar(200) = ''
DECLARE #index int = 1
DECLARE #flag bit = 0
DECLARE #temp varchar(2) = ''
WHILE (#Index <LEN(#string)+1)
BEGIN
SET #temp = SUBSTRING(#string, #Index-1, 1)
--select #temp
IF #temp = ' ' OR #index = 1
BEGIN
SET #ResultString = #ResultString + UPPER(SUBSTRING(#string, #Index, 1))
END
ELSE
BEGIN
SET #ResultString = #ResultString + LOWER(SUBSTRING(#string, #Index, 1))
END
SET #Index = #Index+ 1--increase the index
END
SELECT #ResultString
END
It can be as simple as this:
DECLARE #Name VARCHAR(500) = 'Roger';
SELECT #Name AS Name, UPPER(LEFT(#Name, 1)) + SUBSTRING(#Name, 2, LEN(#Name)) AS CapitalizedName;
fname is column name if fname value is akhil then UPPER(left(fname,1)) provide capital First letter(A) and substring function SUBSTRING(fname,2,LEN(fname)) provide(khil) concate both using + then result is (Akhil)
select UPPER(left(fname,1))+SUBSTRING(fname,2,LEN(fname)) as fname
FROM [dbo].[akhil]
On SQL Server 2016+ using JSON which gives guaranteed order of the words:
CREATE FUNCTION [dbo].[InitCap](#Text NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN STUFF((
SELECT ' ' + UPPER(LEFT(s.value,1)) + LOWER(SUBSTRING(s.value,2,LEN(s.value)))
FROM OPENJSON('["' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(#Text,'\','\\'),'"','\"'),CHAR(9),'\t'),CHAR(10),'\n'),' ','","') + '"]') s
ORDER BY s.[key]
FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'');
END
GO
CREATE FUNCTION [dbo].[Capitalize](#text NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS
BEGIN
DECLARE #result NVARCHAR(MAX) = '';
DECLARE #c NVARCHAR(1);
DECLARE #i INT = 1;
DECLARE #isPrevSpace BIT = 1;
WHILE #i <= LEN(#text)
BEGIN
SET #c = SUBSTRING(#text, #i, 1);
SET #result += IIF(#isPrevSpace = 1, UPPER(#c), LOWER(#c));
SET #isPrevSpace = IIF(#c LIKE '[ -]', 1, 0);
SET #i += 1;
END
RETURN #result;
END
GO
DECLARE #sentence NVARCHAR(100) = N'i-thINK-this soLUTION-works-LiKe-a charm';
PRINT dbo.Capitalize(#sentence);
-- I-Think-This Solution-Works-Like-A Charm
Here is the simplest one-liner to do this:
SELECT LEFT(column, 1)+ lower(RIGHT(column, len(column)-1) ) FROM [tablename]
I was looking for the best way to capitalize and i recreate simple sql script
how to use SELECT dbo.Capitalyze('this is a test with multiple spaces')
result "This Is A Test With Multiple Spaces"
CREATE FUNCTION Capitalyze(#input varchar(100) )
returns varchar(100)
as
begin
declare #index int=0
declare #char as varchar(1)=' '
declare #prevCharIsSpace as bit=1
declare #Result as varchar(100)=''
set #input=UPPER(LEFT(#input,1))+LOWER(SUBSTRING(#input, 2, LEN(#input)))
set #index=PATINDEX('% _%',#input)
if #index=0
set #index=len(#input)
set #Result=substring(#input,0,#index+1)
WHILE (#index < len(#input))
BEGIN
SET #index = #index + 1
SET #char=substring(#input,#index,1)
if (#prevCharIsSpace=1)
begin
set #char=UPPER(#char)
if (#char=' ')
set #char=''
end
if (#char=' ')
set #prevCharIsSpace=1
else
set #prevCharIsSpace=0
set #Result=#Result+#char
--print #Result
END
--print #Result
return #Result
end
IF OBJECT_ID ('dbo.fnCapitalizeFirstLetterAndChangeDelimiter') IS NOT NULL
DROP FUNCTION dbo.fnCapitalizeFirstLetterAndChangeDelimiter
GO
CREATE FUNCTION [dbo].[fnCapitalizeFirstLetterAndChangeDelimiter] (#string NVARCHAR(MAX), #delimiter NCHAR(1), #new_delimeter NCHAR(1))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #result NVARCHAR(MAX)
SELECT #result = '';
IF (LEN(#string) > 0)
DECLARE #curr INT
DECLARE #next INT
BEGIN
SELECT #curr = 1
SELECT #next = CHARINDEX(#delimiter, #string)
WHILE (LEN(#string) > 0)
BEGIN
SELECT #result =
#result +
CASE WHEN LEN(#result) > 0 THEN #new_delimeter ELSE '' END +
UPPER(SUBSTRING(#string, #curr, 1)) +
CASE
WHEN #next <> 0
THEN LOWER(SUBSTRING(#string, #curr+1, #next-2))
ELSE LOWER(SUBSTRING(#string, #curr+1, LEN(#string)-#curr))
END
IF (#next > 0)
BEGIN
SELECT #string = SUBSTRING(#string, #next+1, LEN(#string)-#next)
SELECT #next = CHARINDEX(#delimiter, #string)
END
ELSE
SELECT #string = ''
END
END
RETURN #result
END
GO