stored procedure search with null value - mysql

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;

Related

mySQL Function to make address string

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...

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

stored procedure returns result with 2 params only

hi guys below is my code
USE [arrestedpersonsdb]
GO
/****** Object: StoredProcedure [dbo].[stnencodedtodisplay] Script Date: 08/11/2013 11:18:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[stnencodedtodisplay]
(
#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
,#id int
,#fname varchar
,#lname varchar
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT ROW_NUMBER() OVER
(
ORDER BY [fname] ASC
)AS RowNumber
,[pid]
,[fname]
,[mname]
,[lname]
,[qualifier]
,[alias]
INTO #Results
FROM [todisplay]
where (stnid = #id) and (type = 'STN') and (fname = #fname or #fname = '') and ( lname = #lname or #lname = '')
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
whats odd is that when the #fname and #lname is null it returns the expected result but when i try to pass a parameter on the #fname or #lname it returns nothing
sample below
USE [arrestedpersonsdb]
GO
DECLARE #return_value int,
#RecordCount int
EXEC #return_value = [dbo].[stnencodedtodisplay]
#PageIndex = 1,
#PageSize = 10,
#RecordCount = #RecordCount OUTPUT,
#id = 1599,
#fname = 'ALDRIN',
#lname = ''
SELECT #RecordCount as N'#RecordCount'
SELECT 'Return Value' = #return_value
GO
enter code here
but when i pass the 'ALDRIN' as a parameter for the #fname it returns zero
is there something wrong with my syntax?
You have not specified the size of the varchar parameters.
,#fname varchar
,#lname varchar
Not doing so will give you a size of one.
,#fname varchar(1)
,#lname varchar(1)
Change to whatever is appropriate in your case.
,#fname varchar(100)
,#lname varchar(100)
This might be a caps issue. If so then the following would fix it:
(upper(fname) = upper(#fname) or #fname = '') and
(upper(lname) = upper(#lname) or #lname = '')
or it could be a white space issue in which case the following would fix it
(rtrim(ltrim(fname)) = rtrim(ltrim(#fname)) or #fname = '') and
(rtrim(ltrim(lname)) = rtrim(ltrim(#lname)) or #lname = '')
or both.
I might be late, but another optionto solve the issue is to try this:
SELECT ROW_NUMBER() OVER
(
ORDER BY [fname] ASC
)AS RowNumber
,[pid]
,[fname]
,[mname]
,[lname]
,[qualifier]
,[alias]
INTO #Results
FROM [todisplay]
where stnid = #id
and type = 'STN'
AND CASE WHEN #fname =''
THEN 'True'
ELSE fname
END = CASE WHEN #fname =''
THEN 'True'
ELSE #fname
END
AND CASE WHEN #lname =''
THEN 'True'
ELSE lname
END = CASE WHEN #lname =''
THEN 'True'
ELSE #lname
END
In your current try setting SET ANSI_NULLS OFF.
Hope it helps.

I'm expecting a return type of char, but getting int

can anyone tell me why this returns a type of int?
ALTER PROCEDURE [dbo].[spTableExists] #TableName char(40), #Exists char(5) OUTPUT
AS
IF object_id(#TableName) is not null
select #Exists = 'true'
ELSE
select #Exists = 'false'
I think it's because of #Exists parameter datatype being "char(5)".
Char must be used when data has a fixed lenght.
Try this:
CREATE PROCEDURE [dbo].[spTableExists] #TableName varchar(40), #Exists varchar(5) OUTPUT
AS
SET #Exists = 'false'
IF object_id(#TableName) is not null
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(#TableName) AND type in (N'U'))
BEGIN
SET #Exists = 'true'
END
ELSE
SET #Exists = 'false'
SELECT #Exists
Lacking a set nocount on statement, it is returning a row count. Since it doesn't return any other result, it just does an assignment, that is all you get.

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