Incrementing a combination of nvarchar and numbers [duplicate] - sql

This question already has answers here:
Formatting Numbers by padding with leading zeros in SQL Server
(14 answers)
Closed 9 years ago.
following scenario:
I need to increment a code like this one DS0000001
So next Item would be DS0000002, following DS0000003 and so on.
So for generating this code in a big INSERT Statement I wrote the following function:
CREATE FUNCTION dbo.eufn_e5_importCRM_getNextClientCode(
#partnerCode AS NVARCHAR(10),
#number AS INT
)
RETURNS NVARCHAR(20)
AS
BEGIN
DECLARE #next AS INT
DECLARE #zeroes AS NVARCHAR(10)
DECLARE #nextStr AS NVARCHAR(10)
DECLARE #return AS NVARCHAR(20)
DECLARE #partnerPrefix AS NVARCHAR(10)
SELECT #next = RIGHT(c.clientCode,7) FROM Clients c
SELECT #partnerPrefix = partners.partnerPrefix
FROM partners WHERE partnerCode = #partnerCode
SET #next = ISNULL(#next,0) + #number
SET #nextStr = CONVERT(NVARCHAR(10),#next)
SELECT #zeroes = CASE WHEN #next > 9 THEN '00000'
WHEN #next > 99 THEN '0000'
WHEN #next > 999 THEN '000'
WHEN #next > 9999 THEN '00'
WHEN #next > 99999 THEN '0'
WHEN #next > 999999 THEN ''
ELSE '000000'
END
IF ISNULL(#next,'') = ''
BEGIN
SET #return = #partnerPrefix + #zeroes + '1'
END
ELSE SET #return = #partnerPrefix + #zeroes + #nextStr
RETURN #return
END
#number gets the row number I added in the insert statement manually with the ROW_NUMBER()-function.
This already works fine - it inserts the right code into the table.
What I don't like about the code is this part here:
SELECT #zeroes = CASE WHEN #next > 9 THEN '00000'
WHEN #next > 99 THEN '0000'
WHEN #next > 999 THEN '000'
WHEN #next > 9999 THEN '00'
WHEN #next > 99999 THEN '0'
WHEN #next > 999999 THEN ''
ELSE '000000'
END
I already searched a while on stackoverflow and also googled, but I could not find a function like convert that leaves the "0" standing where they are.
Any ideas how to make this function more flexible and if possible: reusable?
Thanks in advance for any help!

Here's an you can do it like this
Declare #a int
Set #a =8756
Select 'DS' + REPLACE(STR(#a, 7), SPACE(1), '0')
Demo: http://sqlfiddle.com/#!3/d41d8

Related

Change Case to Upper & Lower in SQL Query SELECT

I have a SQL Query to pull a customer name from database, create a customer folder with that name. In the query I am killing slashes and periods, and i am also changing any result containing MCDONALD to SIMPLY "MCDONALDS". So MCDONALDS #123 comes out as simply MCDONALDS. Here is my query.
SELECT
CASE WHEN CHARINDEX('MCDONALD', cust_name) = 0
THEN REPLACE(REPLACE([cust_name],'.',''),'--','-')
ELSE 'MCDONALDS'
END cust_name
FROM job,dbo.cust cust_name
WHERE job.cust_id_bill_to = cust_name.cust_code AND
job.job_id = '44321' AND
job.sub_job_id = '2'
So, results now are:
MCDONALDS,
BRISTOL-MYERS,
TRUMP-CASINO
Desired results is upper and lower case in every word.. like this:
Mcdonalds,
Bristol-Myers,
Trump-Casino
I know its easy but for me its how to have it work WITH the rest of my query, what I am trying just not working so far.
Check Nimit Dudani Answer Here
DELIMITER $$
DROP FUNCTION IF EXISTS `test`.`initcap`$$
CREATE FUNCTION `initcap`(x char(30)) RETURNS char(30) CHARSET utf8
BEGIN
SET #str='';
SET #l_str='';
WHILE x REGEXP ' ' DO
SELECT SUBSTRING_INDEX(x, ' ', 1) INTO #l_str;
SELECT SUBSTRING(x, LOCATE(' ', x)+1) INTO x;
SELECT CONCAT(#str, ' ', CONCAT(UPPER(SUBSTRING(#l_str,1,1)),LOWER(SUBSTRING(#l_str,2)))) INTO #str;
END WHILE;
RETURN LTRIM(CONCAT(#str, ' ', CONCAT(UPPER(SUBSTRING(x,1,1)),LOWER(SUBSTRING(x,2)))));
END$$
DELIMITER ;
Usage:
select initcap('This is test string');
For Sql Server you can use this
INITCAP User defined Function code
IF OBJECT_ID('dbo.InitCap') IS NOT NULL
DROP FUNCTION dbo.InitCap;
GO
CREATE FUNCTION dbo.InitCap (#inStr VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE #outStr VARCHAR(8000) = LOWER(#inStr),
#char CHAR(1),
#alphanum BIT = 0,
#len INT = LEN(#inStr),
#pos INT = 1;
-- Iterate through all characters in the input string
WHILE #pos <= #len BEGIN
-- Get the next character
SET #char = SUBSTRING(#inStr, #pos, 1);
-- If the position is first, or the previous characater is not alphanumeric
-- convert the current character to upper case
IF #pos = 1 OR #alphanum = 0
SET #outStr = STUFF(#outStr, #pos, 1, UPPER(#char));
SET #pos = #pos + 1;
-- Define if the current character is non-alphanumeric
IF ASCII(#char) <= 47 OR (ASCII(#char) BETWEEN 58 AND 64) OR
(ASCII(#char) BETWEEN 91 AND 96) OR (ASCII(#char) BETWEEN 123 AND 126)
SET #alphanum = 0;
ELSE
SET #alphanum = 1;
END
RETURN #outStr;
END
GO
Testing :
SELECT dbo.InitCap('new york');
Result: New York
For your query
SELECT
dbo.InitCap(CASE WHEN CHARINDEX('MCDONALD', cust_name) = 0
THEN REPLACE(REPLACE([cust_name],'.',''),'--','-')
THEN 'MCDONALDS'
END) cust_name
FROM job,dbo.cust cust_name
WHERE job.cust_id_bill_to = cust_name.cust_code AND
job.job_id = '44321' AND
job.sub_job_id = '2'

How to update values using case statement

I have created update statement like below
UPDATE dbo.S_Item
SET SalePrice3 = CASE WHEN Price <0 THEN '-1'
when Price=1 then 11
when Price=2 then 22
when Price=3 then 33
when Price=4 then 44
when Price=5 then 55
when Price=6 then 66
when Price=7 then 77
when Price=8 then 88
when Price=9 then 99
when Price=0 then 00
end
but i want update more values using above statement for example if want update price=123 it has to update 112233,if price=456 it has to update 445566,if price=725 it has to update 772255 how can achieve this help me
Create Function ReplicateDigits (
#Number Int)
Returns BigInt
Begin
Declare #Step SmallInt = 1,
#Result nVaRchar(100) = N''
While (#Step <= Len(#Number))
Begin
Select #Result = #Result + Replicate(SubString(Cast(#Number As Varchar), #Step, 1), 2)
Select #Step = #Step + 1
End
Return Cast(#Result As BigInt)
End
Go
Then:
UPDATE dbo.S_Item
SET SalePrice3 = CASE
WHEN Price <0 THEN '-1'
Else dbo.ReplicateDigits(Price)
End
Let me know if it was useful.
If the point is just in duplication of every digit, here's another implementation of the duplication method:
CREATE FUNCTION dbo.DuplicateDigits(#Input int)
RETURNS varchar(20)
AS
BEGIN
DECLARE #Result varchar(20) = CAST(#Input AS varchar(20));
DECLARE #Pos int = LEN(#Result);
WHILE #Pos > 0
BEGIN
SET #Result = STUFF(#Result, #Pos, 0, SUBSTRING(#Result, #Pos, 1));
SET #Pos -= 1;
END;
RETURN #Result;
END;
The method consists in iterating through the digits backwards, extracting each using SUBSTRING and duplicating it using STUFF.
And you would be using this function same as in Meysam Tolouee's answer:
UPDATE dbo.S_Item
SET SalePrice3 = CASE
WHEN Price < 0 THEN '-1'
ELSE dbo.DuplicateDigits(SalePrice3)
END;
To explain a little why the function's returned type is varchar, it is because that guarantees that the function returns the result no matter what the input's [reasonable] length is. The maximum length of 20 has been chosen merely because the input is [assumed to be] int and positive int values consist of up to 10 digits.
However, whether varchar(20) converts to the type of SalePrice3 is another matter, which should be considered separately.
Youy Must Create a Procedure for Achiving the Desired Result Rather Than to Use a Single Query.

Is it possible to compare rows for similar data in SQL server

Is it possible to compare rows for similar data in SQL Server? I have a company name column in a table where company names could be somewhat similar. Here is an example of the different 8 values that represent the same 4 companies:
ANDORRA WOODS
ANDORRA WOODS HEALTHCARE CENTER
ABC HEALTHCARE, JOB #31181
ABC HEALTHCARE, JOB #31251
ACTION SERVICE SALES, A SUBSIDIARY OF SINGER EQUIPMENT
ACTION SERVICE SALES, A SUBSIDIARY OF SINGER EQUIPMENT COMPANY
APEX SYSTEMS
APEX SYSTEMS, INC
The way I clean it right now is using Google refine where I can identify clusters of similar data values and make them all as one.
Using this example I only need 4 names not 8 so I need to replace similar ones with only one since I will be assigning indexes to those names later on. Any help is greatly appreciated.
I have a couple UDF's I converted from some VB code some time ago that takes in 2 varchar() and returns an int between 0 and 100 (0= not similar, 100= same) if your interested.
-- Description: Removes any special characters from a string
CREATE FUNCTION [dbo].[SimReplaceSpecial]
(
-- Add the parameters for the function here
#String varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE #Result varchar(max) = ''
-- Add the T-SQL statements to compute the return value here
DECLARE #Pos int = 1
DECLARE #Asc int
DECLARE #WorkingString varchar(max)
SET #WorkingString = upper(#String)
WHILE #Pos <= LEN(#WorkingString)
BEGIN
SET #Asc = ascii(substring(#WorkingString,#Pos,1))
If (#Asc >= 48 And #Asc <= 57) Or (#Asc >= 65 And #Asc <= 90)
SET #Result = #Result + Char(#Asc)
SET #Pos = #Pos + 1
--IF #Pos + 1 > len(#String)
-- BREAK
--ELSE
-- CONTINUE
END
-- Return the result of the function
RETURN #Result
END
-- Description: DO NOT CALL DIRECTLY - Used by the Similar function
-- Finds longest common substring (other than single
-- characters) in String1 and String2, then recursively
-- finds longest common substring in left-hand
-- portion and right-hand portion. Updates the
-- cumulative score.
CREATE FUNCTION [dbo].[SimFindCommon]
(
-- Add the parameters for the function here
#String1 varchar(max),
#String2 varchar(max),
#Score int
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
--DECLARE #Result int
DECLARE #Longest Int = 0
DECLARE #StartPos1 Int = 0
DECLARE #StartPos2 Int = 0
DECLARE #J Int = 0
DECLARE #HoldStr varchar(max)
DECLARE #TestStr varchar(max)
DECLARE #LeftStr1 varchar(max) = ''
DECLARE #LeftStr2 varchar(max) = ''
DECLARE #RightStr1 varchar(max) = ''
DECLARE #RightStr2 varchar(max) = ''
-- Add the T-SQL statements to compute the return value here
SET #HoldStr = #String2
WHILE LEN(#HoldStr) > #Longest
BEGIN
SET #TestStr = #HoldStr
WHILE LEN(#TestStr) > 1
BEGIN
SET #J = CHARINDEX(#TestStr,#String1)
If #J > 0
BEGIN
--Test string is sub-set of the other string
If Len(#TestStr) > #Longest
BEGIN
--Test string is longer than previous
--longest. Store its length and position.
SET #Longest = Len(#TestStr)
SET #StartPos1 = #J
SET #StartPos2 = CHARINDEX(#TestStr,#String2)
END
--No point in going further with this string
BREAK
END
ELSE
--Test string is not a sub-set of the other
--string. Discard final character of test
--string and try again.
SET #TestStr = Left(#TestStr, LEN(#TestStr) - 1)
END
--Now discard first char of test string and
--repeat the process.
SET #HoldStr = Right(#HoldStr, LEN(#HoldStr) - 1)
END
--Update the cumulative score with the length of
--the common sub-string.
SET #Score = #Score + #Longest
--We now have the longest common sub-string, so we
--can isolate the sub-strings to the left and right
--of it.
If #StartPos1 > 3 And #StartPos2 > 3
BEGIN
SET #LeftStr1 = Left(#String1, #StartPos1 - 1)
SET #LeftStr2 = Left(#String2, #StartPos2 - 1)
If RTRIM(LTRIM(#LeftStr1)) <> '' And RTRIM(LTRIM(#LeftStr2)) <> ''
BEGIN
--Get longest common substring from left strings
SET #Score = dbo.SimFindCommon(#LeftStr1, #LeftStr2,#Score)
END
END
ELSE
BEGIN
SET #LeftStr1 = ''
SET #LeftStr2 = ''
END
If #Longest > 0
BEGIN
SET #RightStr1 = substring(#String1, #StartPos1 + #Longest, LEN(#String1))
SET #RightStr2 = substring(#String2, #StartPos2 + #Longest, LEN(#String2))
If RTRIM(LTRIM(#RightStr1)) <> '' And RTRIM(LTRIM(#RightStr2)) <> ''
BEGIN
--Get longest common substring from right strings
SET #Score = dbo.SimFindCommon(#RightStr1, #RightStr2,#Score)
END
END
ELSE
BEGIN
SET #RightStr1 = ''
SET #RightStr2 = ''
END
-- Return the result of the function
RETURN #Score
END
-- Description: Compares two not-empty strings regardless of case.
-- Returns a numeric indication of their similarity
-- (0 = not at all similar, 100 = identical)
CREATE FUNCTION [dbo].[Similar]
(
-- Add the parameters for the function here
#String1 varchar(max),
#String2 varchar(max)
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE #Result int
DECLARE #WorkingString1 varchar(max)
DECLARE #WorkingString2 varchar(max)
-- Add the T-SQL statements to compute the return value here
if isnull(#String1,'') = '' or isnull(#String2,'') = ''
SET #Result = 0
ELSE
BEGIN
--Convert each string to simplest form (letters
--and digits only, all upper case)
SET #WorkingString1 = dbo.SimReplaceSpecial(#String1)
SET #WorkingString2 = dbo.SimReplaceSpecial(#String2)
If RTRIM(LTRIM(#WorkingString1)) = '' Or RTRIM(LTRIM(#WorkingString2)) = ''
BEGIN
--One or both of the strings is now empty
SET #Result = 0
END
ELSE
BEGIN
If #WorkingString1 = #WorkingString2
BEGIN
--Strings are identical
SET #Result = 100
END
ELSE
BEGIN
--Find all common sub-strings
SET #Result = dbo.SimFindCommon(#WorkingString1, #WorkingString2,0)
--We now have the cumulative score. Return this
--as a percent of the maximum score. The maximum
--score is the average length of the two strings.
SET #Result = #Result * 200 / (Len(#WorkingString1) + Len(#WorkingString2))
END
END
END
-- Return the result of the function
RETURN #Result
END
--Usage--------------------------------------------------------------------
--Call the "Similar" Function only
SELECT dbo.Similar('ANDORRA WOODS','ANDORRA WOODS HEALTHCARE CENTER')
--Result = 60
SELECT dbo.Similar('ABC HEALTHCARE, JOB #31181','ABC HEALTHCARE, JOB #31251')
--Result = 85
SELECT dbo.Similar('ACTION SERVICE SALES, A SUBSIDIARY OF SINGER EQUIPMENT','ACTION SERVICE SALES, A SUBSIDIARY OF SINGER EQUIPMENT COMPANY')
--Result = 92
SELECT dbo.Similar('APEX SYSTEMS','APEX SYSTEMS, INC')
--Result = 88
SSIS/Data Tools has a Fuzzy Grouping transformation that is very helpful in situations like this. It doesn't actually group your data, rather it gives you similarity scores that you can use to determine when items should be grouped together.
Plenty of tutorials out there, here's one: The Fuzzy Grouping Transformation

How do I convert an int to a zero padded string in T-SQL?

Let's say I have an int with the value of 1. How can I convert that int to a zero padded string, such as 00000001?
Declare #MyInt integer Set #MyInt = 123
Declare #StrLen TinyInt Set #StrLen = 8
Select Replace(Str(#MyInt, #StrLen), ' ' , '0')
Another way is:
DECLARE #iVal int = 1
select REPLACE(STR(#iVal, 8, 0), ' ', '0')
as of SQL Server 2012 you can now do this:
format(#int, '0000#')
This work for me:
SELECT RIGHT('000' + CAST(Table.Field AS VARCHAR(3)),3) FROM Table
...
I created this user function
T-SQL Code :
CREATE FUNCTION CIntToChar(#intVal Int, #intLen Int) RETURNS nvarchar(24) AS BEGIN
IF #intlen > 24
SET #intlen = 24
RETURN REPLICATE('0',#intLen-LEN(RTRIM(CONVERT(nvarchar(24),#intVal))))
+ CONVERT(nvarchar(24),#intVal) END
Example :
SELECT dbo.CIntToChar( 867, 6 ) AS COD_ID
OUTPUT
000867
Use FORMAT(<your number>,'00000000') use as many zeroes as you need to have digits in your final outcome.
Here is official documentation of the FORMAT function
If I'm trying to pad to a specific total length, I use the REPLICATE and DATALENGTH functions, like so:
DECLARE #INT INT
DECLARE #UNPADDED VARCHAR(3)
DECLARE #PADDED VARCHAR(3)
SET #INT = 2
SET #UNPADDED = CONVERT(VARCHAR(3),#INT)
SET #PADDED = REPLICATE('0', 3 - DATALENGTH(#UNPADDED)) + #UNPADDED
SELECT #INT, #UNPADDED, #PADDED
I used variables here for simplicity, but you see, you can specify the final length of the total string and not worry about the size of the INT that you start with as long as it's <= the final string length.
I always use:
SET #padded = RIGHT('z0000000000000'
+ convert(varchar(30), #myInt), 8)
The z stops SQL from implicitly coverting the string into an int for the addition/concatenation.
If the int can go negative you have a problem, so to get around this I sometimes do this:
DECLARE #iVal int
set #iVal = -1
select
case
when #ival >= 0 then right(replicate('0',8) + cast(#ival as nvarchar(8)),8)
else '-' + right(replicate('0',8) + cast(#ival*-1 as nvarchar(8)),8)
end
Very straight forward way to think about padding with '0's is, if you fixed your #_int's to have 4 decimals, you inject 4 '0's:
select RIGHT( '0000'+ Convert(varchar, #_int), 4) as txtnum
; if your fixed space is 3, you inject 3'0's
select RIGHT( '000'+ Convert(varchar, #_int), 3) as txtnum
; below I inject '00' to generate 99 labels for each bldg
declare #_int int
set #_int = 1
while #_int < 100 Begin
select BldgName + '.Floor_' + RIGHT( '00'+ Convert(varchar, #_int), 2)
+ '.balcony' from dbo.tbl_FloorInfo group by BldgName
set #_int = #_int +1
End
Result is:
'BldgA.Floor_01.balcony'
'BldgB.Floor_01.balcony'
'BldgC.Floor_01.balcony'
..
..
'BldgA.Floor_10.balcony'
'BldgB.Floor_10.balcony'
'BldgC.Floor_10.balcony'
..
..
..
'BldgA.Floor_99.balcony'
'BldgB.Floor_99.balcony'
'BldgC.Floor_99.balcony'
Or if you really want to go hard-core... ;-)
declare #int int
set #int = 1
declare #string varchar(max)
set #string = cast(#int as varchar(max))
declare #length int
set #length = len(#string)
declare #MAX int
set #MAX = 8
if #length < #MAX
begin
declare #zeros varchar(8)
set #zeros = ''
declare #counter int
set #counter = 0
while (#counter < (#MAX - #length))
begin
set #zeros = #zeros + '0'
set #counter = #counter + 1
end
set #string = #zeros + #string
end
print #string
And then there's this one, using REPLICATE:
SELECT REPLICATE('0', 7) + '1'
Of course, you can replace the literals 7 and '1' with appropriate functions as needed; the above gives you your example. For example:
SELECT REPLICATE('0', 8 - LEN(CONVERT(nvarchar, #myInt))) + CONVERT(nvarchar, #myInt)
will pad an integer of less than 8 places with zeros up to 8 characters.
Now, a negative number in the second argument of REPLICATE will return NULL. So, if that's a possibility (say, #myInt could be over 100 million in the above example), then you can use COALESCE to return the number without leading zeros if there are more than 8 characters:
SELECT COALESCE(REPLICATE('0', 8 - LEN(CONVERT(nvarchar, #myInt))) + CONVERT(nvarchar, #myInt), CONVERT(nvarchar, #myInt))
I think Charles Bretana's answer is the simplest and fastest. A similar solution without using STR is:
SELECT REPLACE(REVERSE(
CONVERT(CHAR(5 /*<= Target length*/)
, REVERSE(CONVERT(VARCHAR(100), #MyInt)))
), ' ', '0')

T-SQL trim &nbsp (and other non-alphanumeric characters)

We have some input data that sometimes appears with &nbsp characters on the end.
The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.
Ltrim and Rtrim don't remove the characters, so we're forced to do something like:
UPDATE myTable
SET myColumn = replace(myColumn,char(160),'')
WHERE charindex(char(160),myColumn) > 0
This works for the &nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?
This will remove all non alphanumeric chracters
CREATE FUNCTION [dbo].[fnRemoveBadCharacter]
(
#BadString nvarchar(20)
)
RETURNS nvarchar(20)
AS
BEGIN
DECLARE #nPos INTEGER
SELECT #nPos = PATINDEX('%[^a-zA-Z0-9_]%', #BadString)
WHILE #nPos > 0
BEGIN
SELECT #BadString = STUFF(#BadString, #nPos, 1, '')
SELECT #nPos = PATINDEX('%[^a-zA-Z0-9_]%', #BadString)
END
RETURN #BadString
END
Use the function like:
UPDATE TableToUpdate
SET ColumnToUpdate = dbo.fnRemoveBadCharacter(ColumnToUpdate)
WHERE whatever
This page has a sample of how you can remove non-alphanumeric chars:
-- Put something like this into a user function:
DECLARE #cString VARCHAR(32)
DECLARE #nPos INTEGER
SELECT #cString = '90$%45623 *6%}~:#'
SELECT #nPos = PATINDEX('%[^0-9]%', #cString)
WHILE #nPos > 0
BEGIN
SELECT #cString = STUFF(#cString, #nPos, 1, '')
SELECT #nPos = PATINDEX('%[^0-9]%', #cString)
END
SELECT #cString
How is the table being populated? While it is possible to scrub this in sql a better approach would be to change the column type to int and scrub the data before it's loaded into the database (SSIS). Is this an option?
For large datasets I have had better luck with this function that checks the ASCII value. I have added options to keep only alpha, numeric or alphanumeric based on the parameters.
--CleanType 1 - Remove all non alpanumeric
-- 2 - Remove only alpha
-- 3 - Remove only numeric
CREATE FUNCTION [dbo].[fnCleanString] (
#InputString varchar(8000)
, #CleanType int
, #LeaveSpaces bit
) RETURNS varchar(8000)
AS
BEGIN
-- // Declare variables
-- ===========================================================
DECLARE #Length int
, #CurLength int = 1
, #ReturnString varchar(8000)=''
SELECT #Length = len(#InputString)
-- // Begin looping through each char checking ASCII value
-- ===========================================================
WHILE (#CurLength <= (#Length+1))
BEGIN
IF (ASCII(SUBSTRING(#InputString,#CurLength,1)) between 48 and 57 AND #CleanType in (1,3) )
or (ASCII(SUBSTRING(#InputString,#CurLength,1)) between 65 and 90 AND #CleanType in (1,2) )
or (ASCII(SUBSTRING(#InputString,#CurLength,1)) between 97 and 122 AND #CleanType in (1,2) )
or (ASCII(SUBSTRING(#InputString,#CurLength,1)) = 32 AND #LeaveSpaces = 1 )
BEGIN
SET #ReturnString = #ReturnString + SUBSTRING(#InputString,#CurLength,1)
END
SET #CurLength = #CurLength + 1
END
RETURN #ReturnString
END
If the mobile could start with a Plus(+) I will use the function like this
CREATE FUNCTION [dbo].[Mobile_NoAlpha](#Mobile VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE #StartsWithPlus BIT = 0
--check if the mobile starts with a plus(+)
IF LEFT(#Mobile, 1) = '+'
BEGIN
SET #StartsWithPlus = 1
--Take out the plus before using the regex to eliminate invalid characters
SET #Mobile = RIGHT(#Mobile, LEN(#Mobile)-1)
END
WHILE PatIndex('%[^0-9]%', #Mobile) > 0
SET #Mobile = Stuff(#Mobile, PatIndex('%[^0-9]%', #Mobile), 1, '')
IF #StartsWithPlus = 1
SET #Mobile = '+' + #Mobile
RETURN #Mobile
END