I have a set of data for example:
Part no Custom Format
1128005 \Machines\3D\PartNo(2)\PartNo(4)xx\PartNo(7)
11.88.006 \Machines\3D\PartNo(2)\PartNo+3(2)xx\PartNo+6(3)
I want to replace the variable set in the custom format define in it. The result i am looking for is
For Part no
1128005
the result is
\Machines\3D\11\1128xx\1128005
11.88.006
\Machines\3D\11\88xx\006
Any ideas?
Thanks
Regards
If my understanding is correct, below script should be what you want? But because it processes row by row, it can be very slow when dealing with millions of rows.
--declare #input varchar(50) = '11.88.006', #pattern varchar(255) = '\Machines\3D\PartNo(2)\PartNo+3(2)xx\PartNo+6(3)'
declare #input varchar(50) = '1128005', #pattern varchar(255) = '\Machines\3D\PartNo(2)\PartNo(4)xx\PartNo(7)'
declare #tblPattern table (tmpKey int identity(1,1), result varchar(50), Position varchar(50), SkipCnt int, CharLength int, Sufix varchar(50))
declare #i int = 1, #output varchar(max) = '\Machines\3D\'
Declare #PatternXml XML
Set #PatternXml = N'<root><r>' + REPLACE(replace(#pattern, '\Machines\3D\', ''), '\', '</r><r>') + '</r></root>'
insert into #tblPattern(result)
select r.value('.', 'VARCHAR(MAX)') as t
from #PatternXml.nodes('//root//r') as records(r)
update #tblPattern set Position = REPLACE(result, 'PartNo', '')
, SkipCnt = CASE WHEN CHARINDEX('+', result, 1) > 0 THEN SUBSTRING(result, CHARINDEX('+', result, 1) + 1, CHARINDEX('(', result, 1) - CHARINDEX('+', result, 1) - 1) ELSE 0 END
, CharLength = SUBSTRING(result, CHARINDEX('(', result, 1) + 1, CHARINDEX(')', result, 1) - CHARINDEX('(', result, 1) - 1 )
, Sufix = SUBSTRING(result, CHARINDEX(')', result, 1) + 1, LEN(result))
while #i <= 3
begin
select #output += SUBSTRING(#input, 1 + SkipCnt, CharLength) + Sufix + '\'
from #tblPattern
where tmpKey = #i
set #i += 1
end
select #output = STUFF(#output, len(#output), 1, '')
select #output
Related
I have the following two strings:
DECLARE #Str1 VARCHAR(MAX) = 'John A Mak|Street Road UAE'
DECLARE #Str2 VARCHAR(MAX) = '[First Name],[Last Name],[Middle Name]|[Address1],[Address2]'
Note: Both strings are dynamic may comes with more or less values.
Expected result: Want to if any of the given text present in the given columns using the PATINDEX. The following PATINDEX statement gonna used in the WHERE clause of the SELECT statement.
PATINDEX('John',[First Name]) + PATINDEX('A',[First Name]) + PATINDEX('Mak',[First Name]) +
PATINDEX('John',[Last Name]) + PATINDEX('A',[Last Name]) + PATINDEX('Mak',[Last Name]) +
PATINDEX('John',[Middle Name]) + PATINDEX('A',[Middle Name]) + PATINDEX('Mak',[Middle Name]) +
PATINDEX('Street',[Address1]) + PATINDEX('Road',[Address1]) + PATINDEX('UAE',[Address1]) +
PATINDEX('Street',[Address2]) + PATINDEX('Road',[Address2]) + PATINDEX('UAE',[Address2]) > 0
My try:
DECLARE #Str1 VARCHAR(MAX) = 'John A Mak|Street Road UAE'
DECLARE #Str2 VARCHAR(MAX) = '[First Name],[Last Name],[Middle Name]|[Address1],[Address2]'
DECLARE #Length int = 0
DECLARE #Length1 int = 0
DECLARE #Length2 int = 0
DECLARE #Position int = 0
DECLARE #Position1 int = 0
DECLARE #Position2 int = 0
DECLARE #Value varchar(max)
DECLARE #Value1 varchar(max)
DECLARE #Value2 varchar(max)
DECLARE #P_Str2 VARCHAR(MAX) = ''
DECLARE #P_Str3 VARCHAR(MAX) = ''
DECLARE #P_Str1 VARCHAR(MAX) = ''
DECLARE #FinalString VARCHAR(MAX) = ''
SET #P_Str1 = #Str1+'|';
SET #P_Str3 = #Str2+'|';
IF OBJECT_ID('tempdb..#tempt', 'U') IS NOT NULL DROP TABLE #tempt;
CREATE TABLE #tempt(keywords varchar(max));
WHILE CHARINDEX('|', #P_Str3, #Position2+1)>0
BEGIN
set #Length2 = CHARINDEX('|', #P_Str3, #Position2+1) - #Position2
set #Value2 = SUBSTRING(#P_Str3, #Position2, #Length2)
SET #P_Str2 = #Value2+',';
PRINT('--'+#P_Str2);
--WHILE LOOP for creating string for PAT INDEX
WHILE CHARINDEX(',', #P_Str2, #Position+1)>0
BEGIN
set #Length = CHARINDEX(',', #P_Str2, #Position+1) - #Position
set #Value = SUBSTRING(#P_Str2, #Position, #Length)
WHILE CHARINDEX('|', #P_Str1, #Position1+1)>0
BEGIN
set #Length1 = CHARINDEX('|', #P_Str1, #Position1+1) - #Position1
set #Value1 = SUBSTRING(#P_Str1, #Position1, #Length1)
PRINT('Value1--'+#Value1);
PRINT('Value--'+#Value);
INSERT INTO #tempt
SELECT DISTINCT split.a.value('.', 'VARCHAR(100)') AS Keywords
FROM
(
SELECT CAST ('<S>' + REPLACE(ltrim(rtrim(#Value1)), ' ', '</S><S>') + '</S>' AS XML) AS Element
) AS a
CROSS APPLY Element.nodes ('/S') AS split(a)
WHERE split.a.value('.', 'VARCHAR(100)') <> '';
SET #FinalString += STUFF(( SELECT '(PATINDEX('''+keywords+''','+#Value+'),''''0'''') + '
FROM #tempt FOR XML PATH('')), 1,0, '');
DELETE FROM #tempt;
SET #Position1 = CHARINDEX('|', #P_Str1, #Position1+#Length1) +1
END
SET #Position = CHARINDEX(',', #P_Str2, #Position+#Length) +1
END
SET #Position2 = CHARINDEX('|', #P_Str3, #Position2+#Length2) +1
END
PRINT(#FinalString);
But unable to get the expected result.
This is not pretty dynamic SQL, however...
USE Sandbox;
DECLARE #Str1 VARCHAR(MAX) = 'John A Mak|Street Road UAE';
DECLARE #Str2 VARCHAR(MAX) = '[First Name],[Last Name],[Middle Name]|[Address1],[Address2]';
DECLARE #WHERE nvarchar(MAX);
SET #WHERE = STUFF((SELECT N' + ' + NCHAR(10) +
STUFF((SELECT N' + ' +NCHAR(10)+
N'PATINDEX(' + QUOTENAME(DSn.Item,'''') + N',' + DSc.Item + N')' --This trusts no injection.I don't like this.
FROM dbo.DelimitedSplit8K(DS1.Item,' ') DSn
CROSS APPLY dbo.DelimitedSplit8K(DS2.Item,',') DSc
ORDER BY DSc.ItemNumber, DSn.ItemNumber
FOR XML PATH(N'')),1,4,N'')
FROM dbo.DelimitedSplit8K (#Str1,'|') DS1
CROSS APPLY dbo.DelimitedSplit8K (#Str2,'|') DS2
WHERE DS1.ItemNumber = DS2.ItemNumber
ORDER BY DS1.ItemNumber
FOR XML PATH(N'')),1,4,N'') + N' > 0'
SELECT #WHERE;
This outputs:
PATINDEX('John',[First Name]) +
PATINDEX('A',[First Name]) +
PATINDEX('Mak',[First Name]) +
PATINDEX('John',[Last Name]) +
PATINDEX('A',[Last Name]) +
PATINDEX('Mak',[Last Name]) +
PATINDEX('John',[Middle Name]) +
PATINDEX('A',[Middle Name]) +
PATINDEX('Mak',[Middle Name]) +
PATINDEX('Street',[Address1]) +
PATINDEX('Road',[Address1]) +
PATINDEX('UAE',[Address1]) +
PATINDEX('Street',[Address2]) +
PATINDEX('Road',[Address2]) +
PATINDEX('UAE',[Address2]) > 0
Note the use of DelimitedSplit8k, which you'll need on your instance to get this done.
Edit/Note: This is not injection safe. Specifically because of + DSc.Item +. The OP, in their sample data, provides already quoted strings; it is therefore assumed that the strings are properly quoted; I.e. not "[" & ColumnName & "]" (that is still open to injection, as any ] passed won't be escaped). If the columnnames are not properly quoted elsewhere, I strongly suggest removing the brackets ([]) in the passed value and using + QUOTENAME(DSc.Item) + instead.
I have a function we use to convert RTF formatted text to plain text. It has worked pretty well in the past, and seems to work pretty well so far on the text in question.
However, somewhere in my dataset of 230,000 records, it makes a bad SUBSTRING call and aborts the entire thing (without telling me the offending record).
Is there any way I can get some feedback into what is going on?
I know that SQLServer functions do not allow PRINT statements, or INSERT statements.
And the dataset of 230,000 records is not mine, but a clients. I really don't want to have to try to go record by record and see which one is causing the error.
SQL Function below:
CREATE FUNCTION [dbo].[RTF2Text]
(
#rtf nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN
DECLARE #Pos1 int;
DECLARE #Pos2 int;
DECLARE #hex varchar(316);
DECLARE #Stage table
(
[Char] char(1),
[Pos] int
);
INSERT #Stage
(
[Char]
, [Pos]
)
SELECT SUBSTRING(#rtf, [Number], 1)
, [Number]
FROM [master]..[spt_values]
WHERE ([Type] = 'p')
AND (SUBSTRING(#rtf, Number, 1) IN ('{', '}'));
SELECT #Pos1 = MIN([Pos])
, #Pos2 = MAX([Pos])
FROM #Stage;
DELETE
FROM #Stage
WHERE ([Pos] IN (#Pos1, #Pos2));
WHILE (1 = 1)
BEGIN
SELECT TOP 1 #Pos1 = s1.[Pos]
, #Pos2 = s2.[Pos]
FROM #Stage s1
INNER JOIN #Stage s2 ON s2.[Pos] > s1.[Pos]
WHERE (s1.[Char] = '{')
AND (s2.[Char] = '}')
ORDER BY s2.[Pos] - s1.[Pos];
IF ##ROWCOUNT = 0
BREAK
DELETE
FROM #Stage
WHERE ([Pos] IN (#Pos1, #Pos2));
UPDATE #Stage
SET [Pos] = [Pos] - #Pos2 + #Pos1 - 1
WHERE ([Pos] > #Pos2);
SET #rtf = STUFF(#rtf, #Pos1, #Pos2 - #Pos1 + 1, '');
END
SET #rtf = REPLACE(#rtf, '\pard', '^*^');
SET #rtf = REPLACE(#rtf, '\par', '^*^');
SET #rtf = REPLACE(#rtf, '\t', '^~^');
SET #rtf = STUFF(#rtf, 1, CHARINDEX(' ', #rtf), '');
IF len(#rtf) > 0
WHILE (Right(#rtf, 1) IN (' ', CHAR(13), CHAR(10), '}'))
BEGIN
SELECT #rtf = SUBSTRING(#rtf, 1, (LEN(#rtf + 'x') - 2));
IF LEN(#rtf) = 0 BREAK
END
SET #Pos1 = CHARINDEX('\''', #rtf);
WHILE #Pos1 IS NOT NULL AND #Pos1 > 0
BEGIN
IF #Pos1 IS NOT NULL AND #Pos1 > 0
BEGIN
SET #hex = '0x' + SUBSTRING(#rtf, #Pos1 + 2, 2);
SET #rtf = REPLACE(#rtf, SUBSTRING(#rtf, #Pos1, 4), CHAR(CONVERT(int, CONVERT (binary(1), #hex,1))));
SET #Pos1 = CHARINDEX('\''', #rtf);
END
END
SET #rtf = COALESCE(#rtf, '') + ' ';
SET #Pos1 = PATINDEX('%\%[0123456789][\ ]%', #rtf);
WHILE #Pos1 IS NOT NULL AND #Pos1 > 0 AND #rtf != ''
BEGIN
SET #Pos2 = CHARINDEX(' ', #rtf, #Pos1 + 1);
IF #Pos2 < #Pos1
SET #Pos2 = CHARINDEX('\', #rtf, #Pos1 + 1);
IF #Pos2 < #Pos1
BEGIN
SET #rtf = SUBSTRING(#rtf, 1, #Pos1 - 1);
SET #Pos1 = 0;
END
ELSE
BEGIN
SET #rtf = STUFF(#rtf, #Pos1, #Pos2 - #Pos1 + 1, '');
SET #Pos1 = PATINDEX('%\%[0123456789][\ ]%', #rtf);
END
END
IF RIGHT(#rtf, 1) = ' '
SET #rtf = SUBSTRING(#rtf, 1, LEN(#rtf) -1);
RETURN #rtf;
END
Not to be too rude, but have you actually tested on your function?
Have you run any unit tests to try and break your function, e.g. invalid values, boundary conditions etc.?
Have you checked documentation to see under what conditions SUBSTRING can throw an exception?
I have run these cases and am getting exceptions:
SELECT dbo.[RTF2Text]( NULL )
SELECT dbo.[RTF2Text]( '' )
SELECT dbo.[RTF2Text]( '1' )
SELECT dbo.[RTF2Text]( 'blah' )
If you know under what conditions/input values your function will fail, then it is a simple matter of checking for these in your table.
I had a similar situation and have very little knowledge of SQL functions however needed to strip RTF and tried this code. Debugging suggested that this function was failing was here as I was getting Invalid length parameter.
IF RIGHT(#rtf, 1) = ' '
SET #rtf = SUBSTRING(#rtf, 1, LEN(#rtf) -1);
As I have minimal knowledge and lack of time I just added a second if to make sure it wasn't doing a subtraction i.e. -1 from 0 which worked for my dataset.
IF RIGHT(#rtf, 1) = ' '
IF LEN(#rtf) > 0
SET #rtf = SUBSTRING(#rtf, 1, LEN(#rtf) -1);
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
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
How to parse unknown length string into different columns by using delimiter ('.').
declare osversion varchar(100)
set osversion = '6.2.9295'
SELECT [Part1] = LEFT(osversion,CHARINDEX('.',osversion) - 1),
[Part2] = SUBSTRING(osversion,CHARINDEX('.',osversion) + 1,
CHARINDEX('.',osversion,CHARINDEX('.',
osversion) + 1) - (CHARINDEX('.',osversion) + 1)),
[Part3] = SUBSTRING(osversion,CHARINDEX('.',
osversion,CHARINDEX('.',osversion) + 1) + 1,
DATALENGTH(osversion) - CHARINDEX('.',
osversion,CHARINDEX('.',osversion) + 1) -
CHARINDEX('.',REVERSE(osversion))),
from table1
Result:
Part1 Part2 Part3
6 2 9295
This result is for fixed length of string. I want to parse for an unknown length of string.
Like '86.52.929.695.22.1234'. Please help.
I purpose you to recreate the C#'s string.Split function in SQL. Here is the code
CREATE FUNCTION [dbo].[f_Split](
#String NVARCHAR (4000),
#Delimiter NVARCHAR (10)
)
RETURNS #T TABLE ([Value] NVARCHAR(4000))
BEGIN
DECLARE #NEXTSTRING NVARCHAR(4000)
DECLARE #POS INT,#DELIM_SIZE INT
DECLARE #NEXTPOS INT
SELECT
#NEXTSTRING = '',
#String = #String + #Delimiter,
#DELIM_SIZE = LEN(#Delimiter)
SET #POS = CHARINDEX(#Delimiter,#String)
SET #NEXTPOS = 1
WHILE (#POS <> 0)
BEGIN
SET #NEXTSTRING = SUBSTRING(#String,1,#POS - 1)
INSERT INTO #T ( [VALUE]) VALUES (#NEXTSTRING)
SET #String = SUBSTRING(#String,#POS +#DELIM_SIZE,LEN(#String))
SET #NEXTPOS = #POS
SET #POS = CHARINDEX(#Delimiter,#String)
END
RETURN
END
You can call the function like that
DECLARE #temp nvarchar(255); SELECT #temp = '86.52.929.695.22.1234';
SELECT * FROM dbo.f_Split(#temp,'.');
Here is the output :
Value
86
52
929
695
22
1234