I want to create a function that takes a input like (289)648-0997 or 12896480997 abd just returns 2896480997
my code below works for the 12896480997 but not for (289)648-0997
Alter FUNCTION [dbo].[fnFormatPhoneNumber](#phoneNumber VARCHAR(24))
RETURNS VARCHAR(24)
BEGIN
RETURN RIGHT(#phoneNumber, LEN(#phoneNumber) - 1)
END
Go
Try changing your function to this:
Alter FUNCTION [dbo].[fnFormatPhoneNumber](#phoneNumber VARCHAR(24))
RETURNS VARCHAR(24)
BEGIN
SET #phoneNumber = REPLACE(REPLACE(REPLACE(#phoneNumber,'(',''),')',''),'-','')
RETURN RIGHT(#phoneNumber, 10)
END
Go
SELECT [dbo].[fnFormatPhoneNumber]('(289)648-0997')
AND
SELECT [dbo].[fnFormatPhoneNumber]('12896480997') both return:
2896480997
use a case when to distinguish between those that begin with 1 and those that dont.
return
case when left(#phonenumber,1) = 1 then
RIGHT(replace(replace(replace(#phoneNumber, '(',''),')',''),'-','') LEN(#phoneNumber) - 1)
else replace(replace(replace(#phoneNumber, '(',''),')','')'-','') end
if the first char is a 1 then remove it and replace the ()- with ''.
if not just replace the ()-
not too sure on the logic of your input, may be possible to do away with the replace part in the first case when if you wouldnt input a number with ()- and a leading 1.
Related
I am getting this error message
RETURN statements in scalar valued functions must include an argument
when run this query:
create function gender(#gender nvarchar(40))
returns nvarchar(40)
as
begin
(select name,cast(DOB as date) as DOB from datenames where gender = #gender)
return
end
The write way to create a function in mysql for your example is as follows:
DELIMITER \\
create function gender(Igender nvarchar(40))
returns nvarchar(40)
begin
DECLARE customerLevel NVARCHAR(40);
IF EXISTS (select name,cast(DOB as date) as DOB from datenames where gender = Igender) THEN
SET customerLevel = 'SOMETHING1';
ELSE
SET customerLevel = 'SOMETHING2';
END IF;
RETURN (customerLevel);
end
No need to as
No need to # before input
You need to return something.
Don't forget to use DELIMITER.
If you use phpmyadmin and has problem with nvarchar read this post: Unrecognize data type nvarchar in database or simply change it to to varchar.
My database has a table with the following schema:
account(acno,amt)
acno int primary key
amt float(10,2)
How would I write a function that prints all account numbers having odd balance?
This query return odd balance
SELECT acno, amt
FROM
account
WHERE (amt % 2) > 0;
SELECT * FROM account WHERE MOD(amt, .02) > 0;
Should do the trick.
Doesn't really make sense to create function just to do what a simple query can do - that is, just output the rows that match your criteria. If you really need a function I guess you could make one to determine if a number is odd:
CREATE FUNCTION is_odd(amount float) RETURNS BOOLEAN
BEGIN
DECLARE isodd BOOLEAN;
SET isodd = TRUE;
IF MOD(amount,.02) = 0 THEN
SET isodd = FALSE;
END IF;
RETURN (isodd);
END
And then you can use this in the query instead:
SELECT * FROM account where is_odd(amt);
I wrote a function to generate unique id's,its working but sometimes two people are getting same id,I mean duplicates are formed. My unique id looks like
2016-17NLR250001, I deal with only last four digits 0001. I am posting my function please correct it and please help me in avoiding duplicates even though users login into same account or if they do it on same time.
MY FUNCTION:
DELIMITER $$
USE `olmsap`$$
DROP FUNCTION IF EXISTS `fun_generate_uniqueid`$$
CREATE DEFINER=`root`#`%` FUNCTION `fun_generate_uniqueid`( V_DATE DATE,V_MANDALID INT ) RETURNS VARCHAR(30) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE MDLCODE VARCHAR(5);
SET MDLCODE = ' ';
SELECT COUNT(*) INTO #CNT FROM `st_com_mandal` WHERE MANDAL_VS_MC=V_MANDALID;
SELECT dist_mandal_code INTO MDLCODE FROM `st_com_mandal` WHERE MANDAL_VS_MC=V_MANDALID;
IF #CNT>0 THEN
SET #YR=`FUN_FISCAL_YR`(V_DATE);
SELECT CONCAT(IF(DIST_SAN_CODE='GUN','GNT',DIST_SAN_CODE),IFNULL(`dist_mandal_code`,'NULL'))INTO #MANDAL
FROM `st_com_dist` SCD INNER JOIN `st_com_mandal` STM ON STM.`mandal_dist_id`= SCD.`DIST_VC_DC` WHERE MANDAL_VS_MC=V_MANDALID;
IF MDLCODE >0 THEN
SELECT COUNT(Soil_Sample_ID)+1 INTO #ID FROM `tt_mao_soil_sample_dtls` WHERE MANDAL_ID=V_MANDALID AND SUBSTR(UNIQUE_ID,1,7)=#YR ;
ELSE
SELECT COUNT(Soil_Sample_ID)+1 INTO #ID FROM `tt_mao_soil_sample_dtls` WHERE SUBSTR(UNIQUE_ID,1,14)=CONCAT(#YR,#MANDAL) ;
END IF ;
IF LENGTH(#ID)=1 THEN
SET #ID=CONCAT('000',#ID);
ELSEIF LENGTH(#ID)=2 THEN
SET #ID=CONCAT('00',#ID);
ELSEIF LENGTH(#ID)=3 THEN
SET #ID=CONCAT('0',#ID);
ELSE
SET #ID=#ID;
END IF ;
RETURN CONCAT(#YR,#MANDAL,#ID);
ELSE
RETURN 'Mandal Doesnt Exists';
END IF;
END$$
DELIMITER ;
I do not think community will be able to help you with this question. This is a complex function that requires very careful analysis of table / index access and locking.
The only thing I can recommend is to not use existing table data to calculate next sequence as this is a bad practice.
Besides Race conditions that you are experiencing you will also get problems if the record with the last sequence is deleted.
I suggest you read this to get an idea on how to write a custom sequence generator:
http://en.latindevelopers.com/ivancp/2012/custom-auto-increment-values/
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.
I'm having a problem selecting strings from database. The problem is if you have +(123)-4 56-7 in row and if you are searching with a string 1234567 it wouldn't find any results. Any suggestions?
You can use the REPLACE() method to remove special characters in mysql, don't know if it's very efficient though. But it should work.
There is already another thread in SO which covers a very similar question, see here.
If it is always this kind of pattern you're searching, and your table is rather large, I advice against REPLACE() or REGEX() - which ofc will do the job if tweaked properly.
Better add a column with the plain phone numbers, which doesn't contain any formatting character data at all - or even better, a hash of the phone numbers. This way, you could add an index to the new column and search against this. From a database perspective, this is much easier, and much faster.
You can use User Defined Function to get Numeric values from string.
CREATE FUNCTION GetNumeric (val varchar(255)) RETURNS tinyint
RETURN val REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';
CREATE FUNCTION GetNumeric (val VARCHAR(255))
RETURNS VARCHAR(255)
BEGIN
DECLARE idx INT DEFAULT 0;
IF ISNULL(val) THEN RETURN NULL; END IF;
IF LENGTH(val) = 0 THEN RETURN ""; END IF;
SET idx = LENGTH(val);
WHILE idx > 0 DO
IF IsNumeric(SUBSTRING(val,idx,1)) = 0 THEN
SET val = REPLACE(val,SUBSTRING(val,idx,1),"");
SET idx = LENGTH(val)+1;
END IF;
SET idx = idx - 1;
END WHILE;
RETURN val;
END;
Then
Select columns from table
where GetNumeric(phonenumber) like %1234567%;
Query using replace function as -
select * from phoneTable where replace(replace(replace(phone, '+', ''), '-', ''), ')', '(') LIKE '%123%'