I am trying to convert a varchar field to a number, however, there is a set of common characters inside that field that need to be removed in order for me to successfully convert it to numeric.
the name of the field is UKSellPrice1
I need to remove the following strings from UKSellPrice1 BEFORE converting it to numeric:
'.00' '£' 'n/a' '$' '#N/A'
How can I get this done?
at the moment I have the following:
;WITH R0 AS ( SELECT StyleCode ,ColourCode ,UKSellPrice1= CASE WHEN CHARINDEX('.00',UKSellPrice1,1) > 0 THEN REPLACE (UKSellPrice1,'.00','') ELSE UKSellPrice1 END ,UKSellPrice2 FROM dbo.RangePlan ) SELECT * FROM R0
var str = "I have a cat, a dog, and a goat."; str = str. replace(/cat/gi, "dog"); str = str. replace(/dog/gi, "goat"); str = str. replace(/goat/gi, "cat"); //this produces "I have a cat, a cat, and a cat" //but I wanted to produce the string "I have a dog, a goat, and a cat".
Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.
SELECT REPLACE(REPLACE(REPLACE(REPLACE('3*[4+5]/{6-8}', '[', '('), ']', ')'), '{', '('), '}', ')'); We can see that the REPLACE function is nested and it is called multiple times to replace the corresponding string as per the defined positional values within the SQL REPLACE function.
I can think of two approaches.
The first is to use a bunch of nested replace()
statements:
select replace(replace(replace(col, '$', ''), '£', ''), 'n/a', '')
and so on.
The second is to find the first digit and try converting from there. This requires complicated logic with patindex()
. Here is an example:
select cast(left(substring(col, patindex('%[0-9]%', col), 1000), patindex('%[^0-9]%', substring(col, patindex('%[0-9]%', col), 1000)) - 1 ) as int)
You could do this. Create a function to strip a way the unwanted chars like this:
CREATE FUNCTION [dbo].[fnRemovePatternFromString](@BUFFER VARCHAR(MAX), @PATTERN VARCHAR(128)) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @POS INT = PATINDEX(@PATTERN, @BUFFER) WHILE @POS > 0 BEGIN SET @BUFFER = STUFF(@BUFFER, @POS, 1, '') SET @POS = PATINDEX(@PATTERN, @BUFFER) END RETURN @BUFFER END
Then call the scalared function on the column with a pattern like this:
;WITH R0 AS ( SELECT StyleCode ,ColourCode ,UKSellPrice1= CAST(dbo.fnRemovePatternFromString(UKSellPrice1,'%[£$#N/A.00]%') AS INT) ,UKSellPrice2 FROM dbo.RangePlan ) SELECT * FROM R0
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With