SQL WHILE loop inside WHERE clause - sql-server

Can I put a WHILE loop inside WHERE clause? I have a stored procedure where I'm trying to put in text searching capability. I have it working for an exact match like this:
AND (#exactString = ''
OR (CHARINDEX(#exactString, [Short Description]) > 0
OR CHARINDEX(#exactString, [Description]) > 0
OR CHARINDEX(#exactString, [Manufacturer]) > 0))
Next I'm trying to do a "any word" match and an "all words" match. I can get the search string I want to search for with the following WHILE loop:
DECLARE #searchString varchar(max)
DECLARE #endIndex int
SET #allString = LTRIM(RTRIM(#allString))
WHILE LEN(#allString) > 0
BEGIN
SET #endIndex = CHARINDEX(' ', #allString) > 0
IF #endIndex > 0
BEGIN
SET #searchString = LEFT(#allString, #endIndex)
SET #allString = LTRIM(RTRIM(RIGHT(#allString, #endIndex)))
END
ELSE
BEGIN
SET #searchString = #allString
SET #allString = ''
END
END
Now I want to use the #searchString variable like I used #exactString above. Is there a way to do this inside my loop or is there some other technique I'm missing that would work here?
Thanks for your help,
Dan

I have used a table value function to perform this task using a query such as the following:
SELECT I.*
FROM #info AS I
INNER JOIN dbo.funcSplitToTable( ' ', #allString ) AS S
ON I.[Manufacturer] LIKE '%' + S.result + '%'
OR I.[Description] LIKE '%' + S.result + '%'
OR I.[Short Description] LIKE '%' + S.result + '%'
This table value function is defined as follows:
CREATE FUNCTION dbo.funcSplitToTable
/*
Split a string into parts base on a separation character to produce
a table that has one column containing the results of the split.
EXAMPLE:
SELECT * FROM dbo.funcSplitToTable( '~', 'MAINT~12221~10001~10/25/2004~CANCELLED~1' )
SELECT * FROM dbo.funcSplitToTable( '~', '' )
SELECT * FROM dbo.funcSplitToTable( '~', NULL )
SELECT * FROM dbo.funcSplitToTable( NULL, 'MAINT~12221~10001~10/25/2004~CANCELLED~1' )
SELECT * FROM dbo.funcSplitToTable( '', 'MAINT~12221~10001~10/25/2004~CANCELLED~1' )
RETURN:
Table with one column containing resulting strings.
*/
(
#strSearch AS varchar(255) -- String to search for.
,#strText AS varchar(MAX ) -- Text to search for string.
)
RETURNS #tblResult TABLE (
result varchar(MAX) NOT NULL
)
WITH SCHEMABINDING
AS
BEGIN
DECLARE #iLastPos int
DECLARE #iPos int
DECLARE #strResult varchar(MAX)
IF #strText IS NULL RETURN ;
IF #strSearch IS NULL SET #strSearch = '' ;
SET #strResult = NULL ;
SET #iLastPos = 1 ;
SET #iPos = CHARINDEX( #strSearch, #strText ) ;
WHILE #iPos > 0
BEGIN
IF (#iPos - #iLastPos) > 0
INSERT INTO #tblResult
SELECT SUBSTRING( #strText, #iLastPos, (#iPos - #iLastPos) ) AS result
;
SET #iLastPos = #iPos + 1 ;
SET #iPos = CHARINDEX( #strSearch, #strText, #iLastPos ) ;
END
IF (1 + LEN(#strText) - #iLastPos) > 0
INSERT INTO #tblResult
SELECT SUBSTRING( #strText, #iLastPos, (1 + LEN(#strText) - #iLastPos) ) AS result
;
RETURN ;
END

I got a great answer from Michael Erickson that totally works for the "any" search. For the "all" search. I built up an sql string with the entire query. The "all" search section is here:
IF LEN(#allString) > 0
BEGIN
DECLARE #searchString varchar(max)
DECLARE #endIndex int
DECLARE #isFirstString bit
SET #isFirstString = 0
SET #allString = LTRIM(RTRIM(#allString))
WHILE LEN(#allString) > 0
BEGIN
SET #endIndex = CHARINDEX(' ', #allString)
IF #endIndex > 0
BEGIN
SET #searchString = LTRIM(RTRIM(LEFT(#allString, #endIndex)))
SET #allString = LTRIM(RTRIM(RIGHT(#allString, LEN(#allString) - #endIndex)))
END
ELSE
BEGIN
SET #searchString = #allString
SET #allString = ''
END
SET #sql = #sql + ' AND ((CHARINDEX(''' + cast(#searchString as varchar(max)) + ''', [Short Description]) > 0
OR CHARINDEX(''' + cast(#searchString as varchar(max)) + ''', [Description]) > 0
OR CHARINDEX(''' + cast(#searchString as varchar(max)) + ''', [Manufacturer]) > 0))'
END
END
EXEC (#sql)
Thanks again,
Dan

Related

SQL Server : how to remove consecutive duplicate words in a string

Currently I have a dynamic query, generated in the stored procedure, that has a bug. Somehow there is a consecutive duplicate 'AND' generated in it.
Wondering if there is a way to delete the CONSECUTIVE DUPLICATE 'AND' from the dynamic query string.
For eg:
var str = 'Select * from employee A where A.age > 30 AND AND A.role = ''developer'''
Update
The replace as suggested below doesnt work
Please see the below query:
DECLARE
#str NVARCHAR(MAX)
SET #str = 'fasdf asdfasf asfasdfasafsdf AND AND asdfasdfasd AND dfasdfa'
SET #str = REPLACE(#str, 'AND AND', 'AND')
PRINT #str
Thanks!
Something like this?
/****** Object: StoredProcedure [dbo].[RemoveConsecutiveDuplicateTokens] Script Date: 30/06/2016 09:30:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[RemoveConsecutiveDuplicateTokens]
#instr varchar(max) ,
#outstr varchar(max) OUTPUT
as
declare #workstr varchar(max) = ltrim(#instr),
#newstr varchar(max),
#oldtoken varchar(max),
#newtoken varchar(max)
while #workstr is not null
begin
if #oldtoken is null
begin
set #oldtoken = SUBSTRING(#workstr,1,charindex(' ',#workstr))
set #workstr = ltrim(Stuff(#workstr, CharIndex(#oldtoken,#workstr), Len(#oldtoken), ''))
set #newstr = #oldtoken + ' '
end
set #newtoken = SUBSTRING(#workstr,1,charindex(' ',#workstr))
if #newtoken <> #oldtoken
begin
if #newtoken <> char(39)
begin
set #oldtoken = #newtoken
set #newstr = #newstr + #newtoken + ' '
set #workstr = ltrim(Stuff(#workstr, CharIndex(#newtoken,#workstr), Len(#newtoken), ''))
end
end
else
begin
set #workstr = ltrim(Stuff(#workstr, CharIndex(#newtoken,#workstr), Len(#newtoken), ''))
end
if charindex(' ',#workstr) = 0
break
end
set #newtoken = SUBSTRING(#workstr,1,len(#workstr))
if #newtoken <> #oldtoken
begin
if #newtoken <> char(39)
begin
set #oldtoken = #newtoken
set #newstr = #newstr + #newtoken + ' '
set #workstr = ltrim(Stuff(#workstr, CharIndex(#newtoken,#workstr), Len(#newtoken), ''))
end
end
else
begin
set #workstr = ltrim(Stuff(#workstr, CharIndex(#newtoken,#workstr), Len(#newtoken), ''))
end
select #outstr = #newstr
return
First of all, you are doing it wrong. Fix the logic that generates this incorrect sql.
But for research/learning purposes, this is how you do.
REPLACE ( str , 'AND AND' , 'AND')
I forgot how much I dislike SUBSTRING, but then that has been my struggle to read <starting_position> as truly the position the value begins with.
However, the real beast was how string manipulations are implemented in SQL Server under the context of the ##TRANCOUNT.
Consider the statement
PRINT QUOTE_NAME(REPLACE('My____Table', '__', '_'))
We wish to use proper naming standards, but the function returns:
`[My__Table]`
Why? Because REPLACE jumps ahead the length of the duplicates. To prove it, lets add one more '_' CHAR(95) and we get this in return:
`[My___Table]`
So then simply embedding this with a WHILE statement, for example, will be quite sufficient for our needs. Note I replaced the spaces with '_' for readability
DECLARE #instr varchar(max)
SET #instr = 'SELECT * from employee A where A.age > 30 AND AND A.role = ''developer'''
DECLARE #workstr varchar(max) = REPLACE(LTRIM(#instr), ' ', '_'),
#tokenque VARCHAR(MAX),
#newstr INT = 0,
#token varchar(max),
#flag_break INT = 0
-- removes the extra "spaces"
WHILE CHARINDEX('__', #workstr) <> 0
BEGIN
SET #workstr = REPLACE(#workstr, '__' , '_')
END
SET #tokenque = #workstr
WHILE (CHARINDEX('_', #tokenque) <> 0)
BEGIN
SET #token = SUBSTRING(#tokenque, 1, CHARINDEX('_', #Tokenque) - 1 )
IF #token <> '''' -- (') delimiter skipped
BEGIN
WHILE CHARINDEX(#token + '_' + #token, #workstr) <> 0
BEGIN
SET #workstr = REPLACE(#workstr, #token + '_' + #token, #token)
END
SET #tokenque = SUBSTRING(#tokenque, LEN(#token) + 2, LEN(#tokenque) )
END
ELSE SET #tokenque = SUBSTRING(#tokenque, LEN(#token) + 2, LEN(#tokenque) )
PRINT #tokenque --if you want to see the progression
END
PRINT REPLACE(#workstr, '_', ' ')
RESULT:
'SELECT * from employee A where A.age > 30 AND A.role = 'developer'
use the REPLACE function and replace 'AND AND' by 'AND'. example
SELECT REPLACE('Select * from employee A where A.age > 30 AND AND A.role = ''developer'' ','AND AND','AND');

How do I replace non word characters with a dash using TSQL?

How do I replace the characters ~!##$%^&*()_+}{][ in a nvarchar (or varchar) field with a - using TSQL?
you can create user define function for that as given below
CREATE FUNCTION udf_ReplaceSpecialChar
(
#inputString VARCHAR(1000)
)
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE #outputString VARCHAR(1000),
#LENGTH INT,
#index INT,
#char CHAR(1)
SELECT #LENGTH = LEN(#inputString),
#index = 1
WHILE(#index <= #LENGTH)
BEGIN
SET #char = SUBSTRING(#inputString, #index, 1)
IF((ASCII(#char) NOT BETWEEN 65 AND 90) AND (ASCII(#char) NOT BETWEEN 97 AND 122) AND (ASCII(#char) NOT BETWEEN 48 AND 57))
BEGIN
SELECT #inputString = REPLACE(#inputString, #char, '-')
END
SET #index = #index + 1
END
SET #outputString = #inputString
RETURN #outputString
END
SELECT dbo.udf_ReplaceSpecialChar('This()*& is%%#Sample**.>String')
or you should replace each character with '-'
Like
SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('This()*& is%%#Sample**.>String', ' ', '-'), '*', '-'), '#', '-'), '&', '-'), '(', '-'), ')', '-'), '.', '-'), '>', '-'), '%', '-')
You can use REPLACE function. If it doesn't work in some cases, please give us examples.
May be this code is that you are searching for:
-- Author: Christian d'Heureuse, www.source-code.biz
create function dbo.RemoveSpecialChars (#s varchar(256)) returns varchar(256)
with schemabinding
begin
if #s is null
return null
declare #s2 varchar(256)
set #s2 = ''
declare #l int
set #l = len(#s)
declare #p int
set #p = 1
while #p <= #l begin
declare #c int
set #c = ascii(substring(#s, #p, 1))
if #c between 48 and 57 or #c between 65 and 90 or #c between 97 and 122
set #s2 = #s2 + char(#c)
set #p = #p + 1
end
if len(#s2) = 0
return null
return #s2
end
It removes all characters except 0-9, a-z and A-Z. This function uses ASCII codes of characters to determine this ones which must be removed.
--another one variant
----------------------------------------------------------------------------------------
--better to keep such table in server, very usefull table, especially with indexes
DECLARE #Tally TABLE ( N INT )
DECLARE #i AS INT = 1
WHILE #i != 1000
BEGIN
INSERT INTO #Tally
( N )
VALUES ( #i )
SET #i = #i + 1
END
----------------------------------------------------------------------------------------
DECLARE #String AS VARCHAR(1000) = 'This()*& is%%# **.>another one //&^&*$variant'
----------------------------------------------------------------------------------------
--using #tally - split, using like - remove not required, 'for xml ...' - combine into string
SELECT REPLACE(( SELECT LEFT(SUBSTRING(#String, n, 1000), 1)
FROM #Tally AS T
WHERE SUBSTRING(#String, n, 1000) != ''
AND LEFT(SUBSTRING(#String, n, 1000), 1) LIKE '[A-Za-z0-9 ]'
FOR
XML PATH('')
), ' ', ' ')
--another one variant
------------------------------------------------------------------------------------
--better to keep such table in server, very usefull table, especially with indexes
DECLARE #Tally TABLE ( N INT )
DECLARE #i AS INT = 1
WHILE #i != 1000
BEGIN
INSERT INTO #Tally
( N )
VALUES ( #i )
SET #i = #i + 1
END
------------------------------------------------------------------------------------
DECLARE #String VARCHAR(500) ,
#B VARCHAR(500) = ''
SET #String = 'This()*& is%%# **.>another one //&^&*$variant'
SELECT #B = #B + SUBSTRING(#String, t.N, 1)
FROM #Tally t
WHERE t.N <= DATALENGTH(#String)
AND PATINDEX('[A-Za-z0-9 ]', SUBSTRING(#String, t.N, 1)) > 0
SELECT #B
--------------------------------------------------------------------------------
if you wish use this method like a function then:
Create Tally table with one field PRIMARY KEY (1000 rows, starting from 1 with step 1)
Use code below to create function
Table Tally will be very useful for the split sting, clean string etc., currently this is
the best way to use instead fetch, xml and etc.
--------------------------------------------------------------------------------
CREATE FUNCTION [dbo].[StringClean](
#A VARCHAR(500))
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE #B VARCHAR(500)
SET #B = ''
SELECT #B = #B + SUBSTRING(#A, t.N, 1)
FROM dbo.Tally t
WHERE t.N <= DATALENGTH(#A)
AND PATINDEX('[A-Za-z0-9 ]', SUBSTRING(#A, t.N, 1)) > 0
RETURN #B
END
-------------------------------------------------------------------------------
SELECT dbo.StringClean('This()*& is%%# **.>another one //&^&*$variant')
-------------------------------------------------------------------------------
DECLARE #Tally TABLE ( N INT )
DECLARE #i AS INT = 1
WHILE #i != 1000
BEGIN
INSERT INTO #Tally (N) VALUES (#i)
SET #i = #i + 1
END
--------------------------------------------------------------
DECLARE #String VARCHAR(500)
DECLARE #B VARCHAR(500) = ''
DECLARE #ReplacedChars VARCHAR(50) = '~!##$%^&*()_+}{][<>/.'
SET #String = 'This()*& is%%# **.>another one //&^&*$variant'
SELECT #B = #B + CASE WHEN CHARINDEX(SUBSTRING(#String, t.N, 1), #ReplacedChars) > 0 THEN '-'
ELSE SUBSTRING(#String, t.N, 1) END
FROM #Tally t
WHERE t.N <= DATALENGTH(#String)
SELECT #B

Removing special characters and numbers in sql table field

I have a table in sql server 2008 where a column contains field with string and special characters like
abc;#34;pqr. Now I want a function to remove special characters and numbers from that field ;so the output would be like abcpqr.
Try this
DECLARE #str VARCHAR(400)
DECLARE #expres VARCHAR(50) = '%[~,#,#,$,%,&,*,(,),.,!,0-9]%'
SET #str = '(remove) ~special~ 10 *characters. 3 5 from string 1 in sql!'
WHILE PATINDEX( #expres, #str ) > 0
SET #str = Replace(REPLACE( #str, SUBSTRING( #str, PATINDEX( #expres, #str ), 1 ),''),'-',' ')
SELECT #str
REFERENCE
Use The following function
/*********************************
Removes any characters from
#myString that do not meet the
provided criteria.
*********************************/
CREATE FUNCTION dbo.GetCharacters(#myString varchar(500), #validChars varchar(100))
RETURNS varchar(500) AS
BEGIN
While #myString like '%[^' + #validChars + ']%'
Select #myString = replace(#myString,substring(#myString,patindex('%[^' + #validChars + ']%',#myString),1),'')
Return #myString
END
Go
Declare #testStr varchar(1000),
#i int
Set #i = 1
while #i < 255
Select
#TestStr = isnull(#TestStr,'') + isnull(char(#i),''),
#i = #i + 1
Select #TestStr
Select dbo.GetCharacters(#TestStr,'a-z')
Select dbo.GetCharacters(#TestStr,'0-9')
Select dbo.GetCharacters(#TestStr,'0-9a-z')
Select dbo.GetCharacters(#TestStr,'02468bferlki')
Try this :-
DECLARE #var varchar(255) = 'abc;#34;pqr';
SELECT
CONVERT(varchar(255),(
SELECT CASE
WHEN ( ASCII(UPPER(SUBSTRING(#var, Number, 1))) BETWEEN 65 and 90 )
THEN SUBSTRING(#var, Number, 1)
END
FROM
(
Select top(255) number FROM [master]..spt_values
where type = 'p'
) AS n
WHERE Number <= LEN(#var)
FOR XML PATH(''))) as Result
Result
abcpqr

Replace unicode number between to different delimiters with NCHAR function

I've created a MSSQL Server function which encodes special chars (example: हिन्दीabcde fG#) to the unicode number with "#" and ";" as delimiter. Only very simple chars like "abc" will not be encoded:
declare #position int, #txt nvarchar(max), #output as varchar(max);
set #position=1;
set #txt = N'हिन्दीabcde fG#';
set #output = '';
while #position <= len(#txt)
begin
declare #t int;
select #t=unicode(substring(#txt,#position,1))
--print '&#'+ CONVERT(nvarchar(5),#t)+';'
if ( (#t between 48 and 57) OR (#t between 65 and 90) or (#t between 97 and 122) )
BEGIN
SET #output = #output + CONVERT(nvarchar(5), substring(#txt,#position,1) );
END
else
BEGIN
SET #output = #output + '#'+ CONVERT(nvarchar(5),#t)+';'
END
set #position = #position+1
end
Print #output
The result is:
2361;#2367;#2344;#2381;#2342;#2368;abcde#32;fG#35;
I need it for working with ODBC drivers and to avoid problems with special chars.
But now I need the way back - to decode the encoded chars. Is there any smart solution or will I need at least two loops, the "NCHAR" function ...?
I'll try to build such a function - if it's successfull, I'll post it here :)
You might find this approach a little more appealing. First, create a split function that maintains order:
CREATE FUNCTION dbo.SplitStringsOrdered
(
#List NVARCHAR(MAX),
#delim NVARCHAR(10)
)
RETURNS TABLE
AS
RETURN
(
SELECT rn, v = LTRIM(RTRIM(SUBSTRING(#List, rn,
CHARINDEX(#delim, #List + #delim, rn) - rn)))
FROM
(
SELECT TOP (8000) rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2
) AS n
WHERE rn <= LEN(#List)
AND SUBSTRING(#delim + #List, rn, LEN(#delim)) = #delim
);
GO
Usage:
DECLARE #x NVARCHAR(MAX) = N'#2361;#2367;#2344;#2381;'
+ N'#2342;#2368;abcde#32;fG#35;';
-- need one small adjustment to make the string more split-friendly:
SET #x = REPLACE(#x, '#', ';#');
DECLARE #output NVARCHAR(MAX);
SELECT #output = (SELECT
CASE WHEN v LIKE '#%' THEN NCHAR(REPLACE(v, '#', '')) ELSE v END
FROM dbo.SplitStringsOrdered(#x, ';') AS x
ORDER BY rn FOR XML PATH(''),
TYPE).value('./text()[1]','nvarchar(max)');
SELECT #output;
Output:
हिन्दीabcde fG#
I've solved the problem with this query:
declare #position int, #txt nvarchar(max), #output as nvarchar(max), #buffer as varchar(max);
set #position=1;
set #txt = '#2361;#2367;#2344;#2381;#2342;#2368;abcde#32;fG#35;';
set #output = '';
set #buffer = '';
while #position <= len(#txt)
begin
declare #t varchar(max);
select #t=(substring(#txt,#position,1))
if ( len(#buffer) = 0 and #t <> '#' and #t <> ';')
BEGIN
-- Append simple chars, which were not encoded
Print 'Hänge den String ganz normal an den Output: ' + #t
SET #output = #output + #t;
END
ELSE
BEGIN
if ( #t = '#' )
BEGIN
Print 'Raute wurde erkannt: #';
SET #buffer = '#';
END
else if ( #t = ';' )
BEGIN
SET #buffer = REPLACE( #buffer, '#' , '' );
Print 'Umwandeln: ' + #buffer
SET #output = #output + isnull( NCHAR(#buffer) , '');
SET #buffer = '';
END
else
BEGIN
Print 'Ganzzahl an den Buffer anhängen: ' + #t;
SET #buffer = #buffer + #t;
END
END
set #position = #position+1
end
Print #output

How do you prepend space in a string where Upper Case letter comes or where a space really needed [duplicate]

This question already has answers here:
Finding Uppercase Character then Adding Space
(3 answers)
Closed 8 years ago.
How do you prepends space in a string where Upper Case letter comes or where a space really needed.
The Sample code is:
DECLARE #teams TABLE (Team NVARCHAR(100))
INSERT INTO #teams
SELECT 'TataConsultencyServices'
UNION ALL
SELECT 'TataConsultencyCompany'
UNION ALL
SELECT 'CompanyHumanResource'
Expected Result
Tata Consultency Services
Tata Consultency Company
Company Human Resource
A set based solution:
DECLARE #s NVARCHAR(100);
SET #s = 'CompanyHumanResources';
DECLARE #Idx INT = 1;
WITH CteRecursive
AS
(
SELECT 1 AS Idx,
CONVERT(NVARCHAR(200), #s) AS String
UNION ALL
SELECT src.Idx + src.IsUpper + 1,
CONVERT(NVARCHAR(200),
CASE WHEN src.IsUpper = 1 THEN STUFF(src.String, src.Idx+1, 0, ' ') ELSE src.String END
)
FROM
(
SELECT rec.*,
CASE WHEN SUBSTRING(rec.String, rec.Idx, 1) <> ' ' AND SUBSTRING(rec.String, rec.Idx+1, 1) LIKE '[A-Z]' AND SUBSTRING(rec.String, rec.Idx+1, 1) COLLATE Romanian_CS_AS = UPPER(SUBSTRING(rec.String, rec.Idx+1, 1)) COLLATE Romanian_CS_AS THEN 1 ELSE 0 END AS IsUpper
FROM CteRecursive rec
WHERE rec.Idx + 1 <= LEN(rec.String)
) src
)
SELECT TOP(1) x.String
FROM CteRecursive x
ORDER BY x.Idx DESC;
Results:
String
-----------------------
Company Human Resources
You may surely get some help from this:-
CREATE FUNCTION CaseSensitiveSQLSplitFunction
(
#str nvarchar(max)
)
returns #t table (val nvarchar(max))
as
begin
declare #i int, #j int
select #i = 1, #j = len(#str)
declare #w nvarchar(max)
while #i <= #j
begin
if substring(#str,#i,1) = UPPER(substring(#str,#i,1)) collate Latin1_General_CS_AS
begin
if #w is not null
insert into #t (val) select #w
set #w = substring(#str,#i,1)
end
else
set #w = #w + substring(#str,#i,1)
set #i = #i + 1
end
if #w is not null
insert into #t (val) select #w
return
end
Taking the sample as:-
declare #str nvarchar(max) = N'ThisIsATest'
select * from dbo.CaseSensitiveSQLSplitFunction(#str)
set #str = N'ThisIsASqlServerCaseSensitiveSplitStringFunction'
select * from dbo.CaseSensitiveSQLSplitFunction(#str)
It is now possible to sql concatenate string values in a way from rows to single column value.
We can just use any of the sql concatenation function.
declare #str nvarchar(max) = N'ThisIsATest'
SELECT LTRIM(STUFF((
SELECT ' ' + val FROM dbo.CaseSensitiveSQLSplitFunction(#str) FOR XML PATH('')
), 1, 1, '')) string
set #str = N'ThisIsASqlServerCaseSensitiveSplitStringFunction'
SELECT LTRIM(STUFF((
SELECT ' ' + val FROM dbo.CaseSensitiveSQLSplitFunction(#str) FOR XML PATH('')
), 1, 1, '')) string
WHILE 1 = 1
BEGIN
UPDATE #teams
SET TeamName = STUFF(TeamName, patindex('%[a-z,.][A-Z]%', TeamName COLLATE Latin1_General_BIN) + 1,0,' ')
WHERE patindex('%[a-z,.][A-Z]%', TeamName COLLATE Latin1_General_BIN) > 0
IF ##ROWCOUNT = 0 BREAK
END
UPDATE #teams
SET TeamName = STUFF(TeamName, patindex('%[A-Z][a-z]%', RIGHT(TeamName,LEN(TeamName) -1) COLLATE Latin1_General_BIN) +1 ,0,' ')
WHERE patindex('%[A-Z][a-z]%', TeamName COLLATE Latin1_General_BIN) > 0

Resources