Incorrect query result - mysql

I have a query which is not returning correct result:
SELECT t.GroupName AS GroupName, t.ApplicationName AS ApplicationName, t.UserName
FROM UserApplication t
WHERE (#ApplicationName IS NULL OR #ApplicationName = '' OR t.ApplicationName = #ApplicationName) AND
(#UserName IS NULL OR #UserName = '' OR t.UserName= #UserName );
Table structure:
CREATE TABLE userapplication
(`ID` INT,
`ApplicationName` VARCHAR(100),
`GroupName` VARCHAR(100),
`UserName` VARCHAR(100))
When I do not pass any value to the parameter then it showing all rows from the table while if pass any value to the parameter #ApplicationName or #UserName it is giving me same result.
Please help

If you correctly set values of user variables your query will work just fine
SET #ApplicationName = 'App 1';
SET #UserName = '';
SELECT t.GroupName,
t.ApplicationName,
t.UserName
FROM UserApplication t
WHERE (COALESCE(#ApplicationName, '') = ''
OR t.ApplicationName = #ApplicationName)
AND (COALESCE(#UserName, '') = ''
OR t.UserName= #UserName);
It's a little bit more succinct version of your query
Here is SQLFiddle demo

Related

MySQL update if exists else insert throws syntax error

Trying to update existing records based not on ID but specific usernames with no luck. I wrote the following query but I got a syntax error I can't find.
IF EXISTS (SELECT 1 FROM users WHERE username = 'REMOTEUSER1')
THEN
BEGIN
UPDATE users
SET username = 'REMOTEUSER1', password = 'BJxp98YkVbt4', exp_date = '1650991560', member_id = 1, is_mag = '0', play_token = '', reseller_notes = ''
WHERE username = 'REMOTEUSER1'
END;
ELSE
BEGIN
INSERT INTO users (
username,
password,
exp_date,
member_id,
is_new,
play_token,
reseller_notes
) VALUES (
'REMOTEUSER1',
'BJxp98YkVbt4',
'1650991560',
1,
0,
'',
''
)
END;
END IF;
The IF-ELSE conditional statement construct is supported to be used through FUNCTIONS or STORED PROCEDURES that can't use it like a normal query.
If your username column is UNIQUE index or PRIMARY KEY I would use INSERT ... ON DUPLICATE KEY UPDATE Statemen
INSERT INTO users (
username,
password,
exp_date,
member_id,
is_new,
play_token,
reseller_notes
) VALUES (
'REMOTEUSER1',
'BJxp98YkVbt4',
'1650991560',
1,
0,
'',
''
) ON DUPLICATE KEY UPDATE
password = 'BJxp98YkVbt4',
exp_date = '1650991560',
member_id = 1,
is_mag = '0',
play_token = '',
reseller_notes = '';
sqlfiddle
If is_mag is a bit(1) (boolean), then it's likely the update portion where you set it to '0'
either set the boolean to an integer value of 0, or prefix it with b
i.e.
my_bool = b'0'

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

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.

Join two table and then search for the match

I have two table named security_questions and login. Columns in login tables are:
Username, Security_QA_ID, Security_Answer, Security_Attempts,Last_Login,Password_Attempts
where security_questions have:
ID, Name
where Security_QA_ID is referenced with ID
CREATE DEFINER=`satish`#`%` PROCEDURE `p_chkAnswer`(
IN sq VARCHAR(75),
IN sa VARCHAR(20) ,
IN uname VARCHAR(15) ,
out msg INT
)
BEGIN
select (COUNT(*) > 0) INTO #result from login join security_questions on Security_QA_ID = ID where User_Name=uname and Name=sq and Security_Answer=sa;
set msg = #result;
if #result = 1 Then
UPDATE login SET Last_Login=now(),Password_Attempts=0 where User_Name=uname;
else
UPDATE login SET Security_Attempts=Security_Attempts+1 where User_Name=uname;
End if;
END
but in every time only else part get executes. thanks in advance
Your code is quite confusing and hard to read (for me at least), I simplified your statement into a single SELECT so that I can check if your select is correct, and it appears to be correct:
CREATE TABLE `login`
( User_Name text,
Security_QA_ID int(11),
Security_Answer text,
Security_Attempts datetime,
Last_Login datetime,
Password_Attempts int(11)
);
CREATE TABLE `security_questions`
(ID int(11),
Name text
);
INSERT INTO login SET
User_name = 'a',
Security_QA_ID = 1,
Security_Answer = 'c',
Security_Attempts = NOW(),
Last_Login = NOW(),
Password_Attempts = 0;
INSERT INTO security_questions SET
ID = 1,
Name = 'b';
And the select
SELECT IF(COUNT(*) > 0, 1, 0) AS Authenticated
from (login)
LEFT join security_questions on Security_QA_ID = ID
where User_Name='a' and Name='b' and Security_Answer='c'
Do you have to use this DEFINER? wouldn't it be easier to write PHP/Perl/etc code to check for Authenticated as being non-zero?