Find RegExp and Replace specific character - sql-server

I need to find a numeric value + quotes within a string (example 5"). Once found, I need to replace the quote with "pound". Unfortunately, the string is complex:
Sample string
Work and run with Joe "The King" Mel using a 3" vest with "Dog-Bone" weights.
I have tried
SELECT REPLACE(REPLACE('Work and run with Joe "The King" Mel using a 3" vest with "Dog-Bone" weights.', '%[^0-9]"%', 'pound'), '"', 'pound')
But it replaces all the quotes with 'pound'.

This will find the first occurrence of a number followed by a " and replace " with pound.
declare #s varchar(100)
set #s = 'Work and run with Joe "The King" Mel using a 3" vest with "Dog-Bone" weights.'
select stuff(#s, patindex('%[0-9]"%', #s)+1, 1, ' pound')
STUFF
PATINDEX
If you have more than one you can put it in a while loop.
while patindex('%[0-9]"%', #s) > 0
begin
set #s = stuff(#s, patindex('%[0-9]"%', #s)+1, 1, ' pound')
end

If you can't express a deterministic algorithm for the change you want to make, you'll never be able to write a regular expression as an implementation.
You'd written two replace expressions: one replaces only quotes after numbers, but the other replaces all the quotes, period.

If you can use a CLR: http://msdn.microsoft.com/en-us/magazine/cc163473.aspx

Related

SQL - Replace string function is not working as intended

I have a simple string; for example,'01023201580001'.
I would like to replace the last two characters of this string; '01', with '00'.
I could extract the last two characters from this string as RIGHT(columname,2) and then use
REPLACE([columname], RIGHT([columname], 2), '00') as newColumnString
But in the result, it replaces the first two characters as well?
Expected result: 01023201580000
Result I get: 00023201580000
What am I doing wrong?
The second argument to the replace() function defines a pattern to match. The function will look for all instances of that pattern in the target string (first argument) and replace them with the replacement text (third argument).
If you know you only need to change the last two characters, you can take the value excluding those characters and then append the characters you want:
select left(columname, len(columname) - 2) + '00';
If you are doing this for an entire column and some of the rows might not end with '01', you can filter those out:
update MyTable
set columname = left(columname, len(columname) - 2) + '00'
where columname like '%01';
You could also use stuff() in a similar way.
In SQL server, you can use substring like so:
DECLARE #s NVARCHAR(20) = N'01023201580001';
DECLARE #ReplaceWith NVARCHAR(20) = N'00';
SELECT SUBSTRING(#s, 0, LEN(#s) - 1) + #ReplaceWith;
Output: 01023201580000

SQL Server - remove left part of string before a specific character

I have a VARCHAR value that looks like this:
5.95 $ Additional fees
How can I remove everything left from character '$' (including that character) ? So that I get the following result:
Additional fees
The '$' is always present.
STUFF and CHARINDEX would be the simpliest way, in my opinion:
SELECT STUFF(YourColumn,1, CHARINDEX('$',YourColumn),'')
FROM (VALUES('5.95 $ Additional fees'))V(YourColumn);
Note that as $ has a whitespace afterwards, the value returned will have a leading whitespace (' Additional fees'). You could use TRIM (or LTRIM and RTRIM on older versions of SQL Server) to remove this, if it isn't wanted.
I haven't assumed that the portion string to be replaced is CHARINDEX('$',YourColumn)+1, as we have one sample. As far as we know, you could also have values such as '10.99$Base Cost'. If the +1 was used, it would return 'ase Cost' for such a value.
Hello do it like below syntax
declare #temp nvarchar(max)='5.95 $ Additional fees'
select SUBSTRING(#temp,charindex('$',#temp)+1,len(#temp)-1)
You can use SUBSTRING get the particular string and CHARINDEX function to get index of special character, in your case $.
DECLARE #Var VARCHAR(100)
SET #Var = '5.95 $ Additional fees'
SELECT SUBSTRING(#Var, CHARINDEX('$', #Var) + 1, LEN(#Var) - LEN(LEFT(#Var, CHARINDEX('$', #Var))))

I want to compare alphanumeric strings in same column in SQL Server

I have a table with details of family members staying in a particular locality. Since these are government data, it has lot mistakes. Like in one column 'houseno', there a 2 values 'Ti 303' and '303' which are same house numbers.
In the end, I want Ti 303 to be updated with '303'. (As these are family members living in same house)
Similarly 'P-101' and 'P/101' are same houseno's and I want it to be converted to either 'P-101' or 'P/101'. I tried difference, substring etc but of now use to me. Please help!
You just need to strip out the characters to compare the content?
CREATE FUNCTION dbo.FN_GetNumberPart (#strMixedString VARCHAR(200))
RETURNS VARCHAR(200)
AS
BEGIN
DECLARE #NumberPart INT
-- Get the next non numeric character position
SET #NumberPart = PATINDEX('%[^0-9]%', #strMixedString)
-- While there are non numeric characters remaining
WHILE #NumberPart > 0
BEGIN
-- Remove the non numeric character from the string
SET #strMixedString = STUFF(#strMixedString, #NumberPart , 1, '' )
-- Get the next non numeric character position
SET #NumberPart = PATINDEX('%[^0-9]%', #strMixedString)
END
-- Spit out the cleansed string
RETURN ISNULL(#strMixedString,0)
END
GO
SELECT dbo.FN_GetNumberPart(HouseNo)
from TblAddresses
You should use the REPLACE command. For the two examples give you could hard code it as follows:
select REPLACE('Ti 303','Ti ','')
select REPLACE('P-101','P-','P/')
You would use REPLACE in your UPDATE command and not as a SELECT obviously.
If you have a list of strings to replace in a column with an update then you could put these into a table. Then use this in your REPLACE command for the string pattern to be replaced.

Including single quote in data while inserting to database

I have a string "I love McDonald's burgers. it's the best."
and I would like to insert it into a column breaking them into 15 character strings.
Hence I need the result as string inserted in 3 rows
I love McDonald
's burgers. it'
s the best.
But if I use ' ' to include the ', an extra ' is present in the string which will affect my calculation of 15 character breakage.
Is there any other way to include ' without having to use one more ' to escape it?
Please help.
You don't need to add an extra ' if you're breaking the string into a variable:
DECLARE
mcdonald_string VARCHAR2(50) := 'I love McDonald''s burgers. it''s the best.';
BEGIN
WHILE LENGTH(mcdonald_string) > 0 LOOP
INSERT INTO your_table(your_field) VALUES (SUBSTR(mcdonald_string,1,15));
mcdonald_string := SUBSTR(mcdonald_string,16);
END LOOP;
COMMIT;
END;
Doubling the quotation marks within a complicated literal,
particularly one that represents a SQL statement, can be tricky. You
can also use the following notation to define your own delimiter
characters for the literal. You choose a character that is not present
in the string, and then do not need to escape other single quotation
marks inside the literal:
-- q'!...!' notation allows the of use single quotes
-- inside the literal
string_var := q'!I'm a string, you're a string.!';
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/fundamentals.htm#sthref339

SQL: Adding number while REPLACING string

Good evening,
I need to replace a "part of a string" in a SQL column (Column3), I'm using the REPLACE build-in function to accomplish this, but I need to ADD a leading number (1) to the original string (Column2), and I keep getting "String or binary data would be truncated."
UPDATE [database].[dbo].[Table1]
SET [Column3] = REPLACE(Column3, Column2, ('1' + Column2))
One example:
Column2: "0200"
Here is an example of what COLUMN3 string looks like:
Column3: "TEST DATA 0200"
Then after it gets replaced we need to show it like this: "TEST DATA 10200"
Notice the number now includes a leading "1"
HELP PLEASE!!!
Maybe this REPLACE function replaces in a recursive loop until it blows the size of the string. Let's say Column3 is a varchar(10), and contains "abcd". Column2 contains "b". Then, it will replace all occurrences of Column2 in Column3 for '1' + Column2.
First replacement ('b' for '1b'):
"a1bcd"
Second replacement:
"a11bcd"
It keeps going...
"a111bcd"
"a1111bcd"
"a11111bcd"
"a111111bcd"
Next time it will try to put a 11 character string on a varchar(10).
You should define your own function (using T-SQL) to run the string only once and, after replace, continue from after the replacement and not from the right next character.
The error message you are getting indicates that the resulting string is too big to fit in the "Data" column. You need to increase the size of "Data" to ensure the result will fit.
Try running this SELECT (instead of the UPDATE) to see what is happening
SELECT
REPLACE(Column3, Column2, ('1' + Column2)) AS Result,
DATALENGTH(REPLACE(Column3, Column2, ('1' + Column2))) AS ResultSize
FROM
[database].[dbo].[Table1]

Resources