Replace in SQL Server 2008 - sql-server-2008

I have a column A in a table called T. The column is of type nvarchar(255).
There is a trigger on this table that updates the values in column A to a column B in table B. The column B is of type float.
Suppose if there is value 35.1 % in column A, I want to strip off the % and update only 35.1 in column B. It is not necessary that there should be a % symbol for the value in column A.
How do I do this in SQL Server 2008? Any ideas and suggestions are much appreciated!

You may try to use the following query:
update B
set B.colB = cast(REPLACE(A.colA, '%', '') as float)
from A
where B.idB = A.idA

select replace('35.3 %','%','') or select replace('35.3 ','%','') will both return 35.3; just change your query accordingly; something like:
update tableb
set b=replace(valuefromcola,'%','')
where condition

If you want to get only numbers in a string try this function:
CREATE Function [dbo].[GetNumbersFromString](#Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
While PatIndex('%[^0-9]%', #Temp) > 0
Set #Temp = Stuff(#Temp, PatIndex('%[^0-9]%', #Temp), 1, '')
Return #TEmp
End
You should put this inside your trigger. Please note that you'll need to modify the function to accept the . and , characters (due to those being valid in numbers) =-)

--trim trailing non-alphanumeric chars
DECLARE #input nvarchar(4000)
SET #input = ',,, a word $$$'
SELECT REVERSE(SUBSTRING(REVERSE(#input), PATINDEX('%[a-zA-Z0-9]%', REVERSE(#input)), LEN(#input)))

update B
set B.colB = cast(REPLACE(A.colA, '%', '') as float)
from A
where B.idB = A.idA

Related

MySQL Select only part of column

How can i select only a part of a column ? I know I can use substring, but i need to select a string part of a column. As an example: Column can contain the following:
DIRL100
I need to select only the DIRL part in one column, and the 100 part as another.
I could do it with this specific column like so:
SELECT SUBSTRING(column, 5) AS part1,
SUBSTRING(column, 1, 4) AS part2 ....
But i cannot be sure that its always 4 letters (DIRL) before it gets numeric .. Can i somehow use REGEXP or something to extract only the numeric part and the letter part in each column ?
In other words.. Can i split a column by where the letters end. It could as an example contain DIRL100 or AB100200 which should be split into two columns each containing the letters from the column (DIRL or AB) and the digits from the column (100 or 100200) ?
Try this request:
SELECT LEFT(column, patindex('%[0-9]%', column)-1) AS Part1
, RIGHT(column, LEN(column) - patindex('%[0-9]%', column)+1) AS Part2
Unfortunately, the regexp functions in MySQL is limited. You have to write a custom function to help you.
DROP FUNCTION IF EXISTS get_index;
DELIMITER $$
CREATE FUNCTION get_index(targetString VARCHAR(255)) RETURNS INTEGER
BEGIN
DECLARE i INTEGER;
DECLARE min_index INTEGER;
DECLARE current_index INTEGER;
SET i = 0;
SET min_index = NULL;
loopNumbers: WHILE (i <= 9) DO
SET current_index = LOCATE(i, targetString);
IF current_index > 0 THEN
IF min_index IS NULL OR current_index < min_index THEN
SET min_index = current_index;
END IF;
END IF;
SET i = i + 1;
END WHILE;
RETURN(min_index);
END
$$
DELIMITER ;
What this function does is to obtain the first position of the numbers. Then using this function, you can modify your query to:
SELECT SUBSTRING(column_name FROM 1 FOR get_index(column_name)-1) AS first, SUBSTRING(column_name FROM get_index(column_name)) AS second
FROM table_name
WHERE column_name REGEXP '^[a-Z]+[0-9]+$'
The additional WHERE condition is optional to ensure that only data in the correct format is selected.

Substring Binary Data in MYSQL

I have a binary column in my table in mysql. I need to update all the rows for example.
Replace 2nd byte with 1. Doesn't matter what the value was.
SELECT HEX(data) FROM table;
Then
UPDATE table SET data[1] = 1; // the idea
But how do you do something like this in mysql?
Here how you can do it. First get the binary representation with hex function.
Then on the returned value use substring and concat function to replace the 2nd value with 1 and finally update.
Here is an example.
CREATE TABLE t (c BINARY(10));
INSERT INTO t SET c = 'b';
select (HEX(c)) from t;
62000000000000000000
SELECT concat(
substring(HEX(c),1,1),
'1',
substring(HEX(c),3,length(HEX(c)))
)
from t
61000000000000000000
Now putting all together in the update command will replace the value
update t set c = unhex(
concat(
substring(HEX(c),1,1),
'1',
substring(HEX(c),3,length(HEX(c)))
)
);
select (HEX(c)) from t;
61000000000000000000

Remove Non Numeric Values Within SQL Select Statement

I have a value in a database column VALUE:
C_4327
I need to strip the non numeric text from this so that it just leaves the numbers. I have tried using the REPLACE function within SQL but not I don't want to replace, just strip them out. I was previously using PHP to do this:
preg_replace("/[^0-9]/","",$row['VALUE']);
I'm retrieving the value in a SELECT statement.
Your help would be appreciated.
Thanks in advance
If you want to get the number at the end of the string, you can use the following arcane approach:
select reverse(reverse(value) + 0) as NumberAtEnd;
In your case:
value ='C_4327'
reverse(value) = '7234_C'
reverse(value) + 0 = 7234
reverse(reverse(value) + 0) = '4327'
you can create a Function like that/.
CREATE FUNCTION GetNumeric
(
#strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS BEGIN
DECLARE #intAlpha INT
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric)
BEGIN
WHILE
#intAlpha > 0
BEGIN
SET #strAlphaNumeric = STUFF(#strAlphaNumeric, #intAlpha, 1, '' )
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric )
END
END
RETURN ISNULL(#strAlphaNumeric,0)
END
GO
then call the function as follows
SELECT GetNumeric('123456789blahblahblah') AS filedname FROM your_table
you will get the answer : 123456789
simple way: how about substring...
select substr( value, 3 ) from mytable;
it works on your example - but not sure if your real data is more complicated.

How do I extract a value from a varchar column?

I have an SQL Server 2008 database with a table that has a column Data that contains values like this:
Hello\How\Are\You"
Each string in that column has 4 blocks (ie. 3 slash bars)
Question:
How can I extract, using TSQL, the 3rd value (in this case Are) from that column ?
Note that I just care about the 3rd value.
You can use parsename and
replace.
declare #S varchar(30) = 'Hello\How\Are\You'
select parsename(replace(#S, '\', '.'), 2)
if your data is of a more tricky nature, this is one way of doing it:
declare #t1 table(a nvarchar(500))
insert #t1 values('hello/how/are/you')
select left(t2.b, charindex('/', t2.b + '/') - 1)
from #t1 t1
cross apply (select stuff(a,1, charindex('/',a, charindex('/',a) + 1), '') b) t2

Remove trailing zeros in decimal value with changing length

I have a procedure I am doing that displays odds but the client wants only significant digits to be shown. So, 1.50 would show as '1.5' and 1.00 would show as '1'.
How can I get MySQL to not display trailing zeros;
i.e. in the database:
Odds
1.500
23.030
2.000
4.450
would display as
1.5
23.03
2
4.45
Thanks for any help
Easiest way by far, just add zero!
Examples:
SET
#yournumber1="1.500",
#yournumber2="23.030",
#yournumber3="2.000",
#yournumber4="4.450"
;
SELECT
(#yournumber1+0),
(#yournumber2+0),
(#yournumber3+0),
(#yournumber4+0)
;
+------------------+------------------+------------------+------------------+
| (#yournumber1+0) | (#yournumber2+0) | (#yournumber3+0) | (#yournumber4+0) |
+------------------+------------------+------------------+------------------+
| 1.5 | 23.03 | 2 | 4.45 |
+------------------+------------------+------------------+------------------+
1 row in set (0.00 sec)
If the column your value comes from is DECIMAL or NUMERIC type, then cast it to string first to make sure the conversion takes place...ex:
SELECT (CAST(`column_name` AS CHAR)+0) FROM `table_name`;
For a shorter way, just use any built-in string function to do the cast:
SELECT TRIM(`column_name`)+0 FROM `table_name`;
EDIT: I would use the answer below by Christopher McGowan instead - adding 0 to the value, which is better, instead.
It's important to check there is actually a decimal point if doing trimming.
So I think you'd want to use:
SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' from yourfield)) AS yourfield
FROM yourtable
WHERE yourfield LIKE '%.%'
this worked for me.. round the field to 2 decimal places and then trim any trailing zeros
So that 2.10 is 2.1
SELECT trim(round(FIELDNAME,2))+0
FROM tbl_name
....
To remove trailing zeros from a DECIMAL/NUMERIC or string type column, you can simply cast the value to DOUBLE, e.g.:
SELECT CAST(mycol AS DOUBLE) from mytable;
or
SELECT mycol + 0E0 FROM mytable;
In fact, the "cast to char and add zero" trick mentioned in other answers does the same, but in a more indirect (and likely less efficient) way, e.g:
SELECT CAST(mycol AS CHAR)+0 FROM mytable; -- converts to string, then to number
SELECT TRIM(mycol)+0 FROM mytable; -- ditto
Please use below function , it will take care of number having zero without decimal places i.e 150 etc....
SET #saved_cs_client = ##character_set_client;
SET character_set_client = utf8;
DELIMITER $$
USE `mydbname`$$
DROP FUNCTION IF EXISTS `FN_STRIP_TRAILING_ZER0`$$
CREATE DEFINER=`mydbuser`#`%` FUNCTION `FN_STRIP_TRAILING_ZER0`(tNumber DECIMAL(10,7)) RETURNS VARCHAR(20) CHARSET utf8
BEGIN
DECLARE strBuff VARCHAR(20);
DECLARE cnt NUMERIC(2);
DECLARE tString VARCHAR(20);
SELECT CAST(tNumber AS CHAR) INTO tString;
SELECT LOCATE('.',tString) INTO cnt;
IF cnt > 0 THEN
SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM tString)) INTO strBuff;
ELSE
SET strBuff = tString;
END IF;
RETURN strBuff;
END$$
DELIMITER ;
SET character_set_client = #saved_cs_client;
Addendum:
Typically to call this would involve:
SELECT FN_STRIP_TRAILING_ZER0(1.5);
The best solution I found is to cast your round value to FLOAT:
SELECT CAST(ROUND(1.2345984372, 2) AS FLOAT)
Here's what worked for me:
SINGLE COLUMN:
SELECT TRIM(column_name)+0 AS column_name FROM table_name;
MULTIPLE COLUMNS:
SELECT
TRIM(column1)+0 AS column1,
TRIM(column2)+0 AS column2,
TRIM(column3)+0 AS column3,
FROM table_name;
Taking forward the answer provided by #fooquency, if the column is already declared as a DECIMAL with a non-zero value for D in DECIMAL(M, D), we do not need to perform the WHERE condition
WHERE yourfield LIKE '%.%'
as the values in the column will always contain D digits after the decimal dot (.)
If you are using PHP as the scripting language you may use the following:
$var = (float)$var_having_extra_0; // $var = (float) 17.5000
Or use the PHP floatval function:
$var = floatval($var_having_extra_0); // $var = floatval(17.5000)
Using ROUND or CEILING, in the query you just have to type:
SELECT ROUND(2/50)
or
SELECT CEILING(2/50)
I had a similar problem in a situation where I could not modify the code nor the SQL query, but I was allowed to modify the database structure. So I changed the column format from DECIMAL to FLOAT and it solved my problem.
SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' from yourfield)) AS yourfield
FROM yourtable
WHERE yourfield LIKE '%.%'
or
SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' from yourfield)) AS yourfield
FROM yourtable
WHERE instr(yourfield,'.') != 0
work ok but require a "where" clause.
I think the best solution is probably:
SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM ROUND(yourfield,3)))
FROM yourtable
as it doesn't require a "where" clause, doesn't require any special code,
and also lets you set the maximum precision of the number upfront.
Taking fragments of the others answers in this page I came to this conclusion:
SELECT ( IF(
myfield LIKE '%.%',
TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM myfield)),
myfield
) ) FROM mytable
Cheers
SELECT TRIM(TRAILING '0' FROM yourodds)
FROM ...
Docs for the TRIM function.