SQL Command To Trim Output - sql-server

I need to rip out the digits of a number i'm returning. I have them in a listing like X0006, X0130, and X1030. I need to pull out X's and 0's and return 6,130,1030 . I've tried RTRIM like this. Anyone have any ideas on what I need to do? I'm sure i'm missing something easy.
Thanks

Use replace to convert X and O to empty strings, cast to a integer to remove leading zeros.
Sample code below.
-- Simple number table
create table #nums
( my_id int identity(1,1),
my_text varchar(32)
);
-- Simplte test data
insert into #nums (my_text)
values
('X10X30X'),
('O00O30O');
-- Remove characters & convert to int
SELECT CAST (REPLACE(REPLACE(my_text, 'X', ''), 'O', '') AS INT) as my_number
FROM #nums
Sample output below.

Here is a function you can create that will do exactly what you're asking for and any future get digits needs.
CREATE FUNCTION [dbo].[fn__getDigits]
(
#string VARCHAR(50)
)
RETURNS int
AS
BEGIN
-- declare variables
DECLARE
#digits VARCHAR(50),
#length INT,
#index INT,
#char CHAR(1)
-- initialize variables
SET #digits = ''
SET #length = LEN(#string)
SET #index = 0
-- examine each character
WHILE (#length >= #index)
BEGIN
SET #char = SUBSTRING(#string, #index, 1)
SET #index = #index + 1
-- add to the result if the character is a digit
IF (48 <= ASCII(#char) AND ASCII(#char) <= 57)
BEGIN
SET #digits = #digits + #char
END
END
-- return the result
RETURN cast(#digits as int)
END
GO
select [dbo].[fn__getDigits]('X0006')
select [dbo].[fn__getDigits]('X0130')
select [dbo].[fn__getDigits]('X1030')

I used replace to get rid of the X and just copied/pasted into excel to get the preceding zeros off

Related

Converting Varchar to negative decimal in brackets

I want to change a String to a negative decimal value. The string is in the below format:
($421.24)
I want to change this Varchar to decimal to show either -421.24 or (421.24).
I am using Replace function to achieve that but that's not a cool way:
Select convert(decimal(18,2), Replace(Replace(Replace('($421.24)','$', '' ),'(','-'),')','')) -- output -421.24
I want to make it a general sql staement which holds true for both positive and negative numbers. Please suggest.
Here are some shorter options:
Use a single replace to replace both the ( and the $ sign in one go:
Select CAST(Replace(Replace('($421.24)','($', '-'), ')', '') As decimal(18,2))
Use substring instead of replace:
Select CAST('-' + SUBSTRING('($421.24)',3, LEN('($421.24)') - 3) As decimal(18,2))
For SQL Server version 2017 or later, you can use translate, to replace multiple characters in a single command:
Select CAST(TRANSLATE('($421.24)', '($)', ' - ') As decimal(18,2))
Take the string and by using a WHILE loop, take each character and check whether it is a . or a number. If yes then take that character else neglect it and finally cast it to a decimal value.
Query
declare #str as varchar(100) = '($421.24)';
declare #len as int;
select #len = len(#str);
declare #i as int;
set #i = 1;
declare #res as varchar(100) = '';
while(#i <= #len)
begin
declare #c as char(1);
select #c = substring(#str, #i, 1);
select #res+= case when ASCII(#c) = 46 or (ASCII(#c) between 48 and 57)
then #c else '' end;
set #i += 1;
end
select cast(#res as decimal(18, 2)) as [decimal_val];
Find a demo here
Note: You may need to check for multiple dots.
Update
If the string is in a format which cannot convert to a decimal value, then add the below after the WHILE loop.
Query
declare #isnum as bit;
select #isnum = isnumeric(#res);
if(#isnum = 1)
select cast(#res as decimal(18, 2));
else
select 'String cannot convert to a decimal value.';
An other demo

how to find the special characters in a string and split into words in sql server?

I have string like this 'SUZUKI GSX_1300/TWOWHEELER'
Now I want to split the above string into words and inserting the one by one word into one table.
DECLARE #a TABLE (a nvarchar(500));
declare #RTADESC nvarchar(100) = 'SUZUKI GSX_1300/TWOWHEELER';
declare #b int =1;
declare #c int;
set #c=CHARINDEX('_',#RTADESC,#b);
WHILE #c>0
BEGIN
SELECT #b= CHARINDEX('_' ,#RTADESC,#b)+1
INSERT INTO #a
SELECT SUBSTRING(#RTADESC,0,#b-1)
set #c=CHARINDEX('_',#RTADESC,#b)
END
SELECT * FROM #a
Now I want to see the data in the table #a as below
SUZUKI
GSX
1300
TWOWHEELER
Based on it I will search for vehicle makers in my table.
So please help on this how I can split my string I may get different special characters as well in future.
There are some excellent options available at: http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings
There are solutions which allow you to pass the delimiter also, so you could pass in different ones in future.
Create table function func_SplitString
CREATE FUNCTION [dbo].[func_SplitString](#DelimitedString varchar(8000), #Delimiter varchar(100))
RETURNS #tblArray TABLE ( ID int IDENTITY(1,1),Element varchar(1000))
AS
BEGIN
-- Local Variable Declarations
DECLARE #Index smallint,
#Start smallint,
#DelSize smallint
SET #DelSize = LEN(#Delimiter)
-- Loop through source string and add elements to destination table array
WHILE LEN(#DelimitedString) > 0
BEGIN
SET #Index = CHARINDEX(#Delimiter, #DelimitedString)
IF #Index = 0
BEGIN
INSERT INTO #tblArray (Element) VALUES (LTRIM(RTRIM(#DelimitedString)))
BREAK
END
ELSE
BEGIN
INSERT INTO #tblArray (Element) VALUES (LTRIM(RTRIM(SUBSTRING(#DelimitedString, 1,#Index - 1))))
SET #Start = #Index + #DelSize
SET #DelimitedString = SUBSTRING(#DelimitedString, #Start , LEN(#DelimitedString) - #Start + 1)
END
END
RETURN
END
Use the function to split string like this 'SUZUKI GSX_1300/TWOWHEELER'
Replace all special character to '_'
Using func_SplitString
SELECT * FROM func_SplitString (REPLACE(REPLACE('SUZUKI GSX_1300/TWOWHEELER',' ','_'),'/','_'), '_')

return first view not-numeric chars of string in SQL function fails

I am trying to return the prefix of a VAT number with a SQL function. Because of some changes in these numbers and differences in countries and mistakes in the database, the length of the prefix differs from 0 to 4 characters. So the input of my function is a string, with a prefix of not numeric characters and then some numbers. For example ES012345678, and then i only want to return ES.
I wrote a function for it and it fails, it only returns NULL, even when the input is like the example.
Anyone knows where my mistake is?
here is my SQL code:
ALTER FUNCTION [dbo].[returnPreOfVat]
(
-- Add the parameters for the function here
#VATstring varchar
)
RETURNS varchar
AS
BEGIN
-- Declare the return variable here
DECLARE #Result varchar
DECLARE #char varchar(2)
DECLARE #counter int
SET #counter =1;
SET #char = '';
WHILE (#counter < 5) --check some from the front
BEGIN
SET #char = SUBSTRING(#VATstring, #counter,1); --get next char from front
IF(ISNUMERIC(#char)<>1) -- not numeric
BEGIN
SET #Result = #Result + #char;
END
SET #counter=#counter+1;
END
-- Return the result of the function
RETURN #Result
END
you never initialize the result , Please try:
DECLARE #Result varchar = ''
If recall correctly NULL + str = NULL.
I think a loop is overkill here. I'd combine the LEFT and PATINDEX functions
select LEFT(#VATstring, PATINDEX('%[0-9]%', #VATstring)-1)

Number of times a particular character appears in a string

Is there MS SQL Server function that counts the number of times a particular character appears in a string?
There's no direct function for this, but you can do it with a replace:
declare #myvar varchar(20)
set #myvar = 'Hello World'
select len(#myvar) - len(replace(#myvar,'o',''))
Basically this tells you how many chars were removed, and therefore how many instances of it there were.
Extra:
The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example:
declare #myvar varchar(max), #tocount varchar(20)
set #myvar = 'Hello World, Hello World'
set #tocount = 'lo'
select (len(#myvar) - len(replace(#myvar,#tocount,''))) / LEN(#tocount)
Look at the length of the string after replacing the sequence
declare #s varchar(10) = 'aabaacaa'
select len(#s) - len(replace(#s, 'a', ''))
>>6
You can do that using replace and len.
Count number of x characters in str:
len(str) - len(replace(str, 'x', ''))
Use this function begining from SQL SERVER 2016
Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');
-- Output : 3
When This function used with count function it gives you how many
character exists in string
try that :
declare #t nvarchar(max)
set #t='aaaa'
select len(#t)-len(replace(#t,'a',''))
You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()
SELECT
ColName,
DATALENGTH(ColName) -
DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
FROM ColName;
-OR-
Do the replace with 2 characters
SELECT
ColName,
-LEN(ColName)
+LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
FROM ColName;
function for sql server:
CREATE function NTSGetCinC(#Cadena nvarchar(4000), #UnChar nvarchar(100))
Returns int
as
begin
declare #t1 int
declare #t2 int
declare #t3 int
set #t1 = len(#Cadena)
set #t2 = len(replace(#Cadena,#UnChar,''))
set #t3 = len(#UnChar)
return (#t1 - #t2) / #t3
end
Code for visual basic and others:
Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
End Function
It will count occurrences of a specific character
DECLARE #char NVARCHAR(50);
DECLARE #counter INT = 0;
DECLARE #i INT = 1;
DECLARE #search NVARCHAR(10) = 'o'
SET #char = N'Hello World';
WHILE #i <= LEN(#char)
BEGIN
IF SUBSTRING(#char, #i, 1) = #search
SET #counter += 1;
SET #i += 1;
END;
SELECT #counter;
Use this code, it is working perfectly.
I have create a sql function that accept two parameters, the first param is the long string that we want to search into it,and it can accept string length up to 1500 character(of course you can extend it or even change it to text datatype).
And the second parameter is the substring that we want to calculate the number of its occurance(its length is up to 200 character, of course you can change it to what your need). and the output is an integer, represent the number of frequency.....enjoy it.
CREATE FUNCTION [dbo].[GetSubstringCount]
(
#InputString nvarchar(1500),
#SubString NVARCHAR(200)
)
RETURNS int
AS
BEGIN
declare #K int , #StrLen int , #Count int , #SubStrLen int
set #SubStrLen = (select len(#SubString))
set #Count = 0
Set #k = 1
set #StrLen =(select len(#InputString))
While #K <= #StrLen
Begin
if ((select substring(#InputString, #K, #SubStrLen)) = #SubString)
begin
if ((select CHARINDEX(#SubString ,#InputString)) > 0)
begin
set #Count = #Count +1
end
end
Set #K=#k+1
end
return #Count
end

How do you count the number of occurrences of a certain substring in a SQL varchar?

I have a column that has values formatted like a,b,c,d. Is there a way to count the number of commas in that value in T-SQL?
The first way that comes to mind is to do it indirectly by replacing the comma with an empty string and comparing the lengths
Declare #string varchar(1000)
Set #string = 'a,b,c,d'
select len(#string) - len(replace(#string, ',', ''))
Quick extension of cmsjr's answer that works for strings with more than one character.
CREATE FUNCTION dbo.CountOccurrencesOfString
(
#searchString nvarchar(max),
#searchTerm nvarchar(max)
)
RETURNS INT
AS
BEGIN
return (LEN(#searchString)-LEN(REPLACE(#searchString,#searchTerm,'')))/LEN(#searchTerm)
END
Usage:
SELECT * FROM MyTable
where dbo.CountOccurrencesOfString(MyColumn, 'MyString') = 1
You can compare the length of the string with one where the commas are removed:
len(value) - len(replace(value,',',''))
The answer by #csmjr has a problem in some instances.
His answer was to do this:
Declare #string varchar(1000)
Set #string = 'a,b,c,d'
select len(#string) - len(replace(#string, ',', ''))
This works in most scenarios, however, try running this:
DECLARE #string VARCHAR(1000)
SET #string = 'a,b,c,d ,'
SELECT LEN(#string) - LEN(REPLACE(#string, ',', ''))
For some reason, REPLACE gets rid of the final comma but ALSO the space just before it (not sure why). This results in a returned value of 5 when you'd expect 4. Here is another way to do this which will work even in this special scenario:
DECLARE #string VARCHAR(1000)
SET #string = 'a,b,c,d ,'
SELECT LEN(REPLACE(#string, ',', '**')) - LEN(#string)
Note that you don't need to use asterisks. Any two-character replacement will do. The idea is that you lengthen the string by one character for each instance of the character you're counting, then subtract the length of the original. It's basically the opposite method of the original answer which doesn't come with the strange trimming side-effect.
Building on #Andrew's solution, you'll get much better performance using a non-procedural table-valued-function and CROSS APPLY:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* Usage:
SELECT t.[YourColumn], c.StringCount
FROM YourDatabase.dbo.YourTable t
CROSS APPLY dbo.CountOccurrencesOfString('your search string', t.[YourColumn]) c
*/
CREATE FUNCTION [dbo].[CountOccurrencesOfString]
(
#searchTerm nvarchar(max),
#searchString nvarchar(max)
)
RETURNS TABLE
AS
RETURN
SELECT (DATALENGTH(#searchString)-DATALENGTH(REPLACE(#searchString,#searchTerm,'')))/NULLIF(DATALENGTH(#searchTerm), 0) AS StringCount
Declare #string varchar(1000)
DECLARE #SearchString varchar(100)
Set #string = 'as as df df as as as'
SET #SearchString = 'as'
select ((len(#string) - len(replace(#string, #SearchString, ''))) -(len(#string) -
len(replace(#string, #SearchString, ''))) % 2) / len(#SearchString)
Accepted answer is correct ,
extending it to use 2 or more character in substring:
Declare #string varchar(1000)
Set #string = 'aa,bb,cc,dd'
Set #substring = 'aa'
select (len(#string) - len(replace(#string, #substring, '')))/len(#substring)
Darrel Lee I think has a pretty good answer. Replace CHARINDEX() with PATINDEX(), and you can do some weak regex searching along a string, too...
Like, say you use this for #pattern:
set #pattern='%[-.|!,'+char(9)+']%'
Why would you maybe want to do something crazy like this?
Say you're loading delimited text strings into a staging table, where the field holding the data is something like a varchar(8000) or nvarchar(max)...
Sometimes it's easier/faster to do ELT (Extract-Load-Transform) with data rather than ETL (Extract-Transform-Load), and one way to do this is to load the delimited records as-is into a staging table, especially if you may want an simpler way to see the exceptional records rather than deal with them as part of an SSIS package...but that's a holy war for a different thread.
If we know there is a limitation on LEN and space, why cant we replace the space first?
Then we know there is no space to confuse LEN.
len(replace(#string, ' ', '-')) - len(replace(replace(#string, ' ', '-'), ',', ''))
Use this code, it is working perfectly.
I have create a sql function that accept two parameters, the first param is the long string that we want to search into it,and it can accept string length up to 1500 character(of course you can extend it or even change it to text datatype).
And the second parameter is the substring that we want to calculate the number of its occurance(its length is up to 200 character, of course you can change it to what your need). and the output is an integer, represent the number of frequency.....enjoy it.
CREATE FUNCTION [dbo].[GetSubstringCount]
(
#InputString nvarchar(1500),
#SubString NVARCHAR(200)
)
RETURNS int
AS
BEGIN
declare #K int , #StrLen int , #Count int , #SubStrLen int
set #SubStrLen = (select len(#SubString))
set #Count = 0
Set #k = 1
set #StrLen =(select len(#InputString))
While #K <= #StrLen
Begin
if ((select substring(#InputString, #K, #SubStrLen)) = #SubString)
begin
if ((select CHARINDEX(#SubString ,#InputString)) > 0)
begin
set #Count = #Count +1
end
end
Set #K=#k+1
end
return #Count
end
In SQL 2017 or higher, you can use this:
declare #hits int = 0
set #hits = (select value from STRING_SPLIT('F609,4DFA,8499',','));
select count(#hits)
Improved version based on top answer and other answers:
Wrapping the string with delimiters ensures that LEN works properly. Making the replace character string one character longer than the match string removes the need for division.
CREATE FUNCTION dbo.MatchCount(#value nvarchar(max), #match nvarchar(max))
RETURNS int
BEGIN
RETURN LEN('[' + REPLACE(#value,#match,REPLICATE('*', LEN('[' + #match + ']') - 1)) + ']') - LEN('['+#value+']')
END
DECLARE #records varchar(400)
SELECT #records = 'a,b,c,d'
select LEN(#records) as 'Before removing Commas' , LEN(#records) - LEN(REPLACE(#records, ',', '')) 'After Removing Commans'
The following should do the trick for both single character and multiple character searches:
CREATE FUNCTION dbo.CountOccurrences
(
#SearchString VARCHAR(1000),
#SearchFor VARCHAR(1000)
)
RETURNS TABLE
AS
RETURN (
SELECT COUNT(*) AS Occurrences
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY O.object_id) AS n
FROM sys.objects AS O
) AS N
JOIN (
VALUES (#SearchString)
) AS S (SearchString)
ON
SUBSTRING(S.SearchString, N.n, LEN(#SearchFor)) = #SearchFor
);
GO
---------------------------------------------------------------------------------------
-- Test the function for single and multiple character searches
---------------------------------------------------------------------------------------
DECLARE #SearchForComma VARCHAR(10) = ',',
#SearchForCharacters VARCHAR(10) = 'de';
DECLARE #TestTable TABLE
(
TestData VARCHAR(30) NOT NULL
);
INSERT INTO #TestTable
(
TestData
)
VALUES
('a,b,c,de,de ,d e'),
('abc,de,hijk,,'),
(',,a,b,cde,,');
SELECT TT.TestData,
CO.Occurrences AS CommaOccurrences,
CO2.Occurrences AS CharacterOccurrences
FROM #TestTable AS TT
OUTER APPLY dbo.CountOccurrences(TT.TestData, #SearchForComma) AS CO
OUTER APPLY dbo.CountOccurrences(TT.TestData, #SearchForCharacters) AS CO2;
The function can be simplified a bit using a table of numbers (dbo.Nums):
RETURN (
SELECT COUNT(*) AS Occurrences
FROM dbo.Nums AS N
JOIN (
VALUES (#SearchString)
) AS S (SearchString)
ON
SUBSTRING(S.SearchString, N.n, LEN(#SearchFor)) = #SearchFor
);
I finally write this function that should cover all the possible situations, adding a char prefix and suffix to the input. this char is evaluated to be different to any of the char conteined in the search parameter, so it can't affect the result.
CREATE FUNCTION [dbo].[CountOccurrency]
(
#Input nvarchar(max),
#Search nvarchar(max)
)
RETURNS int AS
BEGIN
declare #SearhLength as int = len('-' + #Search + '-') -2;
declare #conteinerIndex as int = 255;
declare #conteiner as char(1) = char(#conteinerIndex);
WHILE ((CHARINDEX(#conteiner, #Search)>0) and (#conteinerIndex>0))
BEGIN
set #conteinerIndex = #conteinerIndex-1;
set #conteiner = char(#conteinerIndex);
END;
set #Input = #conteiner + #Input + #conteiner
RETURN (len(#Input) - len(replace(#Input, #Search, ''))) / #SearhLength
END
usage
select dbo.CountOccurrency('a,b,c,d ,', ',')
Declare #MainStr nvarchar(200)
Declare #SubStr nvarchar(10)
Set #MainStr = 'nikhildfdfdfuzxsznikhilweszxnikhil'
Set #SubStr = 'nikhil'
Select (Len(#MainStr) - Len(REPLACE(#MainStr,#SubStr,'')))/Len(#SubStr)
this T-SQL code finds and prints all occurrences of pattern #p in sentence #s. you can do any processing on the sentence afterward.
declare #old_hit int = 0
declare #hit int = 0
declare #i int = 0
declare #s varchar(max)='alibcalirezaalivisualization'
declare #p varchar(max)='ali'
while #i<len(#s)
begin
set #hit=charindex(#p,#s,#i)
if #hit>#old_hit
begin
set #old_hit =#hit
set #i=#hit+1
print #hit
end
else
break
end
the result is:
1
6
13
20
I ended up using a CTE table for this,
CREATE TABLE #test (
[id] int,
[field] nvarchar(500)
)
INSERT INTO #test ([id], [field])
VALUES (1, 'this is a test string http://url, and https://google.com'),
(2, 'another string, hello world http://example.com'),
(3, 'a string with no url')
SELECT *
FROM #test
;WITH URL_count_cte ([id], [url_index], [field])
AS
(
SELECT [id], CHARINDEX('http', [field], 0)+1 AS [url_index], [field]
FROM #test AS [t]
WHERE CHARINDEX('http', [field], 0) != 0
UNION ALL
SELECT [id], CHARINDEX('http', [field], [url_index])+1 AS [url_index], [field]
FROM URL_count_cte
WHERE CHARINDEX('http', [field], [url_index]) > 0
)
-- total urls
SELECT COUNT(1)
FROM URL_count_cte
-- urls per row
SELECT [id], COUNT(1) AS [url_count]
FROM URL_count_cte
GROUP BY [id]
Using this function, you can get the number of repetitions of words in a text.
/****** Object: UserDefinedFunction [dbo].[fn_getCountKeywords] Script Date: 22/11/2021 17:52:00 ******/
DROP FUNCTION IF EXISTS [dbo].[fn_getCountKeywords]
GO
/****** Object: UserDefinedFunction [dbo].[fn_getCountKeywords] Script Date: 2211/2021 17:52:00 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: m_Khezrian
-- Create date: 2021/11/22-17:52
-- Description: Return Count Keywords In Input Text
-- =============================================
Create OR Alter Function [dbo].[fn_getCountKeywords]
(#Text nvarchar(max)
,#Keywords nvarchar(max)
)
RETURNS #Result TABLE
(
[ID] int Not Null IDENTITY PRIMARY KEY
,[Keyword] nvarchar(max) Not Null
,[Cnt] int Not Null Default(0)
)
/*With ENCRYPTION*/ As
Begin
Declare #Key nvarchar(max);
Declare #Cnt int;
Declare #I int;
Set #I = 0 ;
--Set #Text = QUOTENAME(#Text);
Insert Into #Result
([Keyword])
Select Trim([value])
From String_Split(#Keywords,N',')
Group By [value]
Order By Len([value]) Desc;
Declare CntKey_Cursor Insensitive Cursor For
Select [Keyword]
From #Result
Order By [ID];
Open CntKey_Cursor;
Fetch Next From CntKey_Cursor Into #Key;
While (##Fetch_STATUS = 0) Begin
Set #Cnt = 0;
While (PatIndex(N'%'+#Key+'%',#Text) > 0) Begin
Set #Cnt += 1;
Set #I += 1 ;
Set #Text = Stuff(#Text,PatIndex(N'%'+#Key+'%',#Text),len(#Key),N'{'+Convert(nvarchar,#I)+'}');
--Set #Text = Replace(#Text,#Key,N'{'+Convert(nvarchar,#I)+'}');
End--While
Update #Result
Set [Cnt] = #Cnt
Where ([Keyword] = #Key);
Fetch Next From CntKey_Cursor Into #Key;
End--While
Close CntKey_Cursor;
Deallocate CntKey_Cursor;
Return
End
GO
--Test
Select *
From dbo.fn_getCountKeywords(
N'<U+0001F4E3> MARKET IMPACT Euro area Euro CPIarea annual inflation up to 3.0% MaCPIRKET forex'
,N'CPI ,core,MaRKET , Euro area'
)
Go
Reference https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver15
Example:
SELECT s.*
,s.[Number1] - (SELECT COUNT(Value)
FROM string_split(s.[StringColumn],',')
WHERE RTRIM(VALUE) <> '')
FROM TableName AS s
Applies to: SQL Server 2016 (13.x) and later
You can use the following stored procedure to fetch , values.
IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[sp_parsedata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_parsedata]
GO
create procedure sp_parsedata
(#cid integer,#st varchar(1000))
as
declare #coid integer
declare #c integer
declare #c1 integer
select #c1=len(#st) - len(replace(#st, ',', ''))
set #c=0
delete from table1 where complainid=#cid;
while (#c<=#c1)
begin
if (#c<#c1)
begin
select #coid=cast(replace(left(#st,CHARINDEX(',',#st,1)),',','') as integer)
select #st=SUBSTRING(#st,CHARINDEX(',',#st,1)+1,LEN(#st))
end
else
begin
select #coid=cast(#st as integer)
end
insert into table1(complainid,courtid) values(#cid,#coid)
set #c=#c+1
end
The Replace/Len test is cute, but probably very inefficient (especially in terms of memory).
A simple function with a loop will do the job.
CREATE FUNCTION [dbo].[fn_Occurences]
(
#pattern varchar(255),
#expression varchar(max)
)
RETURNS int
AS
BEGIN
DECLARE #Result int = 0;
DECLARE #index BigInt = 0
DECLARE #patLen int = len(#pattern)
SET #index = CHARINDEX(#pattern, #expression, #index)
While #index > 0
BEGIN
SET #Result = #Result + 1;
SET #index = CHARINDEX(#pattern, #expression, #index + #patLen)
END
RETURN #Result
END
Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.

Resources