mySQL Function to make address string - mysql

I want to have a mySQL function that returns a string which is based on input parameters. So I have no blanks.
I tried the following but it tells me there is a syntax error at the beginning but I cannot see it.
CREATE DEFINER = CURRENT_USER FUNCTION `NewProc`(`add1` varchar,`add2` varchar,`add3` varchar,`town` varchar,`USState` varchar,`pcode` varchar,`country` varchar)
RETURNS varchar(250)
BEGIN
DECLARE fulladdress VARCHAR;
fulladdress = add1;
if (add2 <>'')
{fulladdress = CONCAT(fulladdress,', ',add2);}
if (add3 <> '')
{fulladdress = CONCAT(fulladdress,', ',add3);}
fulladdress = CONCAT(fulladdress,', ',town);
if (USState <> '')
{fulladdress = CONCAT(fulladdress,', ',USState);}
if (pcode <> '')
{fulladdress = CONCAT(fulladdress', ',pcode;}
fulladdress = CONCAT(fulladdress,', ',country)};
RETURN fulladdress;
END;

I would use the concat_ws function instead, then you would only have to specify the separator once, and it ignores null parameter values. Note that you'll have to adjust the size of the varchar parameters to fit your needs. Something like this should give the desired result:
DELIMITER //
CREATE DEFINER = CURRENT_USER
FUNCTION `NewProc`(
add1 varchar(20),
add2 varchar(20),
add3 varchar(20),
town varchar(20),
USState varchar(20),
pcode varchar(20),
country varchar(20)
)
RETURNS varchar(250)
BEGIN
DECLARE fulladdress VARCHAR(250);
if (add2 = '') then set add2 = null; end if;
if (add3 = '') then set add3 = null; end if;
if (town = '') then set town = null; end if;
if (USState = '') then set USState = null; end if;
if (pcode = '') then set pcode = null; end if;
RETURN concat_ws(', ', add1, add2, add3, town, USState, pcode, country);
END //
DELIMITER ;
The function can probably be written in a smarter way, but my knowledge of MySQL is rather limited...

Related

how to declare variables in trigger with mysql?

CREATE OR REPLACE TRIGGER ATTENDANCE_NOTIFY AFTER INSERT OR UPDATE ON ATTENDANCE
FOR EACH ROW
DECLARE
V_STUDENT_ID STUDENT.STUDENT_ID%TYPE := NULL;
V_HOD_ID HEAD_OF_DEPARTMENT.HOD_ID%TYPE := NULL;
V_SUBCODE STUDENT.SUBCODE%TYPE := NULL;
V_ATTENDANCE ATTENDENCE%TYPE := NULL;
BEGIN
SELECT SUB_CODE, SUB_NAME INTO V_SUB_CODE, FROM SUBJECT WHERE STUDENT_ID = :NEW.STUDENT_ID;
SELECT STUDENT_ID INTO V_STUDENT_ID FROM STUDENT WHERE SUBJECT_CODE = :NEW.SUBJECT_CODE;
SELECT HOD_ID INTO V_HOD_ID FROM STUDENT_HOD WHERE STUDENT_ID = :NEW.STUDENT_ID;
SELECT ATTENDENCE INTO V_ATTENDENCE FROM ATTENDENCE WHERE STUDENT_ID=:NEW_STUDENT_ID
IF (V_ATTENDENCE IS NOT NULL AND V_SUB_CODE IS NOT NULL AND V_STUDENT_ID IS NOT NULL AND V_HOD_ID IS NOT NULL) THEN
IF (:NEW.ATTENDENCE < (V_ATTENDENCE * 0.85)) THEN
INSERT INTO NOTIFY VALUES(V_HOD_ID, V_STUDENT_ID || ' (ID:- ' || :NEW.STUDENT_ID ||') HAS LESS THAN 85% ATTENDENCE IN SUBJECT ' || V_SUB_CODE);
END IF;
END IF;
EXCEPTION
WHEN OTHERS
THEN NULL;
END;
i am getting a syntax error in declare
There is no way to refer datatype of column in MySQL. DECLARE must statically declare a variable's type and size.
Something like
DECLARE myvar VARCHAR( 8 ) -- This is valid in Mysql
Not
DECLARE myvar mytable.myfield%TYPE --This is invalid in Mysql
Hope this helps.

stored procedure search with null value

my query for supplier_search is..
CREATE DEFINER=`root`#`localhost` PROCEDURE `supplier_Search`(in strLedgerName varchar(255),in strAddress varchar(255),
in inPhoneNo int(45), in inMobNo int(45), in strPriceLevel varchar(255),in strCountry varchar(255),in strState varchar(255))
BEGIN
if inPhoneNo = '' then SET inPhoneNo =Null ;end if;
if inMobNo = '' then SET inMobNo =Null ;end if;
if strLedgerName ='' then SET strLedgerName = Null; end if;
if strAddress ='' then set strAddress = null; end if;
if strPriceLevel = '' then set strPriceLevel = null; end if;
if strCountry = '' then set strCountry = null; end if;
if strState = '' then set strState = null; end if;
select ledgerName,address, phoneNo , mobNo ,priceLevel,stateName, CountryName from
(
select joined_ab.ledgerName,joined_ab.address ,joined_ab.phoneNo, joined_ab.mobNo ,joined_ab.priceLevel,c.countryName,joined_ab.stateId
from (select a.ledgerName, a.address , a.phoneNo , a.mobNo ,b.priceLevel,
a.countryId,a.stateId from tbl_ledger as a inner join tbl_price_level as b on a.pricingLevelId =b.priceLevelId)
as joined_ab inner join tbl_country as c on joined_ab.countryId = c.countryId
) as joined_abc inner join tbl_state
as d on joined_abc.stateId = d.stateId
where((strLedgerName is null or joined_abc.ledgerName LIKE concat(strLedgerName,"%"))
and(strAddress is null or address LIKE concat(strAddress ,"%"))
and(inPhoneNo is Null or phoneNo lIke concat(inPhoneNo , "%"))
and (strPriceLevel is null or priceLevel Like concat(strPriceLevel,"%"))
and(inMobNo is Null or mobNo Like concat(inMobNo , "%"))
and(strCountry is null or CountryName LikE concat(strCountry,"%"))
and(strState is null or StateName LikE concat(strState,"%")));
END
i want to get output when one or more than one value is passed.
but the problem is when i'm not passing value for mobileNo or phoneNo and executes the error is
call db_account.supplier_Search('1', '', '', '', '', '', '')
Error Code: 1366. Incorrect integer value: '' for column 'inPhoneNo' at row 1 0.000 sec
The problem is due to the fact You're passing an integer value as ''.
SQL doesn't know which type of integer is; try setting 0 or NULL.
The environment is suggesting you which the issue is: you're using '' as an integer value, SQL doesn't know which type of integer is; try setting 0 or NULL. If the problem is not in the calling operation you have to change the way you compare data in the body of the procedure:
if inPhoneNo = '' then SET inPhoneNo =Null ;end if;

MySQL stored procedure will execute but conditions not working

MySQL stored procedure will execute but conditions are not working. Could someone clear up this issue?
The empty value is not checking with or condition. Does it need a replacement for or?
DELIMITER $$
CREATE DEFINER=`rebar`#`%` PROCEDURE `SearchInProgress`(
ClientID bigint,
GCName varchar(250),
TeamID int,
USPMID Bigint,
JobReceivedDate datetime,
importanceID Bigint
)
begin
select * from jobdetails
where
(clientid = ClientID or ClientID = "") and
(GCName = GCName or GCName ="") and
(TeamID = TeamID or TeamID ="") and
(ReceivedDate = JobReceivedDate or JobReceivedDate = "") and
(ImportanceID = importanceID or importanceID = "") and
(JobID in (select jobid from JobCoordinatorDetails where USProjectManagerID = USPMID) );
end
I think it could be brackets
This (clientid = ClientID or ClientID = "") could be written like this
(clientid = ClientID) OR (ClientID = "" )
Its justa thought. I might be wrong
DELIMITER $$
DROP PROCEDURE if exists SearchInProgress $$
CREATE PROCEDURE `SearchInProgress`(
aclientID bigint,
aGCName varchar(250),
aTeamID int,
aUSProjectManagerID bigint,
aReceivedDate datetime,
aImportanceID bigint
)
begin
select * from jobdetails
where
(clientid = aclientID or aclientID = '') and
(GCName = aGCName or aGCName = '') and
(TeamID = aTeamID or aTeamID = '') and
(ReceivedDate = aReceivedDate or aReceivedDate = '0000-00-00 00:00:00') and
(ImportanceID = aImportanceID or aImportanceID = '') and
(JobID in (select jobid
from JobCoordinatorDetails
where USProjectManagerID = aUSProjectManagerID) or aUSProjectManagerID = '')
;
end
The parameter name and the column name must be different. I've prepended a to the parameter names.
An empty datetime value is replaced by '0000-00-00 00:00:00': https://dev.mysql.com/doc/refman/5.7/en/datetime.html

Mysql WHERE IN (*)

I have a procedure A which takes an array of strings. By calling another procedure B, i break this array in this format:
'1','2','3','4'
In case there is only one value, it just displays as '1'
I want to return * in case the array passed to the procedure A.
Therefore, my query will be like this: select * from users where userId(*);
What i want is that in case the parameter is null, it should still perform the IN using.
** EDIT **
Nothing much of query
CREATE DEFINER=`root`#`localhost` PROCEDURE `listAll`(IN id varchar(200))
BEGIN
set #t = lib_explode(',',id);
select * from city where ID in(#t);
END
Procedure B
CREATE DEFINER=`root`#`localhost` FUNCTION `lib_explode`(sSepar VARCHAR(255), saVal TEXT) RETURNS varchar(200) CHARSET utf8
body:
BEGIN
IF sSepar IS NULL OR saVal IS NULL THEN LEAVE body; END IF;
SET #saTail = saVal;
SET #iSeparLen = LENGTH( sSepar );
set #mystring = '';
set #current_pos = 1;
create_layers:
WHILE #saTail != '' DO
# Get the next value
SET #sHead = SUBSTRING_INDEX(#saTail, sSepar, 1);
SET #saTail = SUBSTRING( #saTail, LENGTH(#sHead) + 1 + #iSeparLen );
-- INSERT INTO lib_Explode SET val = #sHead;
if(#current_pos > 1) then
set #mystring = concat(#mystring,',',concat("'",#shead,"'"));
else
set #mystring = concat(#mystring,concat("'",#shead,"'"));
end if;
set #current_pos = #current_pos + 1;
END WHILE;
return #mystring;
END

mysql replace regular expression what ever in the braces in a string

Below are the few rows of a column data in my mysql database
Data
test(victoryyyyy)king
java(vaaaarrrryy)side
(vkittt)sap
flex(vuuuuu)
k(vhhhhyyy)kk(abcd)k
In all rows there is random string that starts with
(v
and ends with
)
My task :- I have to replace all string from '(v' to ')' with empty space ( that is ' ') I shouldn't touch other values in the braces , in the above case I should not replace (abcd) in the last row
I mean for the above example the result should be
test king
java side
sap
flex
kkk(abcd)k
Could any one please help me ?
Thank You
Regards
Kiran
Mysql doesn't support regexes for replace tasks.
So you can only use string functions to find and substr necessary part.
I wrote my own function for this and it is working . Thanks every one .
drop FUNCTION replace_v;
CREATE FUNCTION replace_v (village varchar(100)) RETURNS varchar(100)
DETERMINISTIC
BEGIN
DECLARE a INT Default 0 ;
DECLARE lengthofstring INT Default 0 ;
DECLARE returnString varchar(100) Default '' ;
DECLARE charString varchar(100) Default '' ;
DECLARE found char(1) default 'N';
declare seccharString varchar(100) Default '' ;
set lengthofstring = length(village);
simple_loop: LOOP
SET a=a+1;
set charString=substr(village,a,1);
if(charString = '(') then
set seccharString=substr(village,a+1,1);
if( seccharString = 'v' || seccharString = 'V' || seccharString = 'p' || seccharString = 'P'
|| seccharString = 'm' || seccharString = 'M' ) then
set found='y';
end if;
end if ;
if(found='n') then
set returnString = concat (returnString,charString);
end if;
if(charString = ')') then
set found='n';
end if ;
IF a>=lengthofstring THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
if ( found = 'y') then
set returnString =village;
end if;
RETURN (replace( returnString,'&', ' '));
END