What am I missing on my query below?
When I'm passing parameter for (#Status) 'All' , there were no results even though the #status parameter condition is satisfied.
Since when I pass 'All' it will be changed to (un-assigned, assigned). But when I'm passing Assigned/ Un-Assigned directly, it works fine.
ALTER PROCEDURE [dbo].[sp_File_Search]
#Uploaded AS INT = null,
#File_Name AS VARCHAR(150) = null,
#Upload_DT AS DATETIME = null,
#Status AS VARCHAR(150) = null,
#St1 AS VARCHAR(15) = null,
#St2 AS VARCHAR(15) = null
AS
If #Status = 'All'
BEGIN
SET #St1 = 'Un-Assigned'
SET #St2 = 'Assigned'
END
ELSE
BEGIN
SET #St1 = #Status
SET #St2 = #Status
END
--ON UPLOAD DATE
Begin
if #Uploaded= 1
Begin
SELECT [FILE_ID],[FILE_NAME], [UPLOAD_DT] FROM [dbo].[FILE]
WHERE (
[FILE_NAME] like '%' + #File_Name + '%'
OR #File_Name IS NULL
)
AND (
[UPLOAD_DT] between #Upload_DT + '00:00:00' and #Upload_DT + '23:59:59'
OR #Upload_DT IS NULL OR #Upload_DT = ''
)
AND (
[STATUS] IN (#St1,#St2)
Order by Upload_DT desc
END
-- ON OR BEFORE UPLOAD DATE
if #Uploaded=2
Begin
SELECT [FILE_ID],[FILE_NAME], [UPLOAD_DT]
FROM [cobind].[FILE]
WHERE (
[FILE_NAME] like '%' + #File_Name + '%'
OR #File_Name IS NULL
)
AND (
[UPLOAD_DT] between #Upload_DT + '00:00:00' and #Upload_DT + '23:59:59'
OR [UPLOAD_DT] < #Upload_DT
OR #Upload_DT IS NULL OR #Upload_DT = ''
)
AND (
[STATUS] IN (#St1,#St2)
)
Order by Upload_DT desc
END
-- ON OR AFTER UPLPOAD DATE
if #Uploaded=3
Begin
SELECT [FILE_ID], [FILE_NAME], [UPLOAD_DT]
FROM [dbo].[FILE]
WHERE (
[FILE_NAME] like '%' + #File_Name + '%'
OR #File_Name IS NULL
)
AND (
[UPLOAD_DT] between #Upload_DT + '00:00:00' and #Upload_DT + '23:59:59'
OR [UPLOAD_DT] > #Upload_DT
OR #Upload_DT IS NULL OR #Upload_DT = ''
)
AND (
[STATUS] IN (#St1,#St2)
)
Order by Upload_DT desc
END
END
The IN keyword works with either a subquery or a list. When you create the list of values in the SET #Status statement, you are actually creating a string. The query will try to look for the specific string, and since that string does not exist in the column being searched, there won't be any results.
You can work around this by using dynamic SQL. Basically, create a variable to hold the part related to #Status, create the query itself as an NVARCHAR string and append your variable clause to it. Finally, use sp_executesql to run the query, something like this:
If #Status = 'All'
SET #Status = '(''Un-Assigned'',''Assigned'')'
declare #query nvarchar(1000) = 'SELECT * FROM [dbo].[CoM_REPO] WHERE [STATUS] IN ' + #Status + ' Order by UploadDATE desc'
exec sp_executesql #query
Are you getting any error message ?
I guess its because your query says [STATUS] IN (#Status) , meaning () are already there, so if you pass Assigned , it would be coming as [STATUS] IN ('Assigned'), whereas when you are passing 'All', it may be coming as [STATUS] IN ((''Un-Assigned'',''Assigned'')) with double brackets, just try to remove the brackets.
Related
I am executing this stored procedure and it works fine, but when I am calling from the frontend side, it returns no rows.
ALTER PROCEDURE [dbo].[USP_GetRequest_DataListForViewPrint]
#RequestNo VARCHAR(50) = null,
#FromDate varchar(50) = null,
#ToDate varchar(50) = null
AS
BEGIN
DECLARE #SQLStr varchar(8000), #WHERECRI VARCHAR(1000) = NULL
IF (#RequestNo IS NOT NULL)
BEGIN
SET #WHERECRI = 'WHERE RequestNo='+ CHAR(39)+#RequestNo+ CHAR(39) ;
END
ELSE
BEGIN
SET #WHERECRI = ' WHERE RequestDate BETWEEN ' + CHAR(39) + CONVERT(varchar(10), CONVERT(datetime, #FromDate, 105), 102) + CHAR(39) + 'AND' + CHAR(39) + CONVERT(varchar(10), CONVERT(datetime, #ToDate, 105), 102) + CHAR(39);
END
SET #SQLStr = 'SELECT Id, RequestStatus, RequestDate, RequestNo FROM CYGNUX_Request_Header ' + #WHERECRI;
PRINT #SQLStr;
EXEC(#SQLStr);
END
In the frontend it take parameter this way and this is does not return any data:
EXEC USP_GetRequest_DataListForViewPrint '', '08-06-2020 00:00:00','16-06-2020 00:00:00'
But if I execute this in SQL Server this way it is returning data. I don't know what's wrong in my frontend
EXEC USP_GetRequest_DataListForViewPrint null, '08-06-2020 00:00:00','16-06-2020 00:00:00'
Please help me - how can I solve this?
In the frontend you are not passing NULL but an empty string, therefor your SP is executing the Select with a WHERE on RequestNo equal to an empty string which probably doesn't return any record.
Is there a better way to obtain the following?
DECLARE #Desc VARCHAR(200) = ''
SELECT [id],
[Desc],
[Col1],
[Col2]
FROM [dbo].[tbl]
WHERE [Desc] LIKE CASE
WHEN #Desc LIKE ''
THEN [Desc]
ELSE '%'+ #Desc +'%'
END
This allows to return all values if the parameter is not defined (#Desc='') or return a subset of values (#Desc='test').
Use OR Operator instead of Case
DECLARE #Desc VARCHAR(200) = ''
SELECT [id],
[Desc],
[Col1],
[Col2]
FROM [dbo].[tbl]
WHERE
(
ISNULL(#Desc,'')=''
)
OR
(
ISNULL(#Desc,'')<>''
AND
[Desc] LIKE '%'+ #Desc +'%'
)
Execution Plan Difference using Both Logics
Using Case
Using Or
It's better for the execution engine to do as much parameter handling prior to the query.
DECLARE #Desc VARCHAR(200) = '';
DECLARE #SelectAll bit;
SET #SelectAll = CASE WHEN #Desc = '' THEN 1 ELSE 0 END;
SET #Desc = CASE WHEN #Desc = '' THEN #Desc ELSE ('%' + #Desc + '%') END;
SELECT [id],
[Desc],
[Col1],
[Col2]
FROM [dbo].[tbl]
WHERE
(#SelectAll = 1)
OR
(#SelectAll = 0 AND [Desc] LIKE #Desc);
If you don't mind code duplication, you can take it even further and do two separate queries split by IF / ELSE.
If you use null you save some steps
declare #userId int = null;
SELECT TOP 1000 [AuctionId]
,[UserId]
,[BiddingPrice]
,[DateTime]
FROM [Test].[dbo].[Bid]
WHERE isnull(#userId, [UserId]) = [UserId];
Well, As Aaron Bertrand commented, your current query can be written simply like this:
DECLARE #Desc VARCHAR(200) = ''
SELECT [id],
[Desc],
[Col1],
[Col2]
FROM [dbo].[tbl]
WHERE [Desc] LIKE '%'+ #Desc +'%'
Since if #Desc contains an empty string, it will result with [Desc] LIKE '%%' -so all records where [Desc] is not null will be returned anyway.
If #Desc can be passed as null, use Coalesce to convert null to an empty string:
...WHERE [Desc] LIKE '%'+ COALESCE(#Desc, '') +'%'
Please note that in both questions, records where the Desc column contains null will not be returned. If that is a nullable column and you want to also return the records where it's null and the #Desc parameter is also null or empty, then you should use OR:
SELECT [id],
[Desc],
[Col1],
[Col2]
FROM [dbo].[tbl]
WHERE [Desc] LIKE '%'+ #Desc +'%'
OR (COALESCE(#Desc, '') = '' AND [Desc] IS NULL)
Also, please note that this is only because of your use of LIKE - Should you try to evaluate conditions using a different operator (such as =, <, >etc') you should use the OR syntax like in the other answers.
Ok, I've been staring at this for too long and I can't figure it out. How long? Too long. What is the cause of the error? It points to the THEN statement.
DECLARE #lp varchar(30) = '307856874'
DECLARE #item varchar(30) = '%'
DECLARE #loc varchar(8) = '%'
DECLARE #lot varchar(20) = '%'
DECLARE #trans_type varchar(20) = '%'
DECLARE #trans_date datetime = NULL;
DECLARE #desc varchar(20) = '%'
DECLARE #whse varchar(20) = '%'
DECLARE #qty decimal = NULL;
SELECT
t.lp_num,
t.item,
t.loc,
t.lot,
t.trans_type,
t.trans_date,
t.description,
t.whse,
t.qty,
t.u_m,
t.emp_num,
t.ref_num,
t.ref_line_suf,
t.createdate,
t.FGLotCode,
t.Uf_Shift,
t.Uf_shift_start_date,
t.Uf_TruckID,
t.Uf_EdiExtracted
FROM
ISW_LPTrans AS t
WHERE
LTRIM(RTRIM((t.lp_num))) LIKE #lp AND
t.item LIKE #item AND
t.loc LIKE #loc AND
t.lot LIKE #lot AND
t.trans_type LIKE #trans_type AND
(#trans_date IS NULL OR t.trans_date = #trans_date) AND
t.description LIKE #desc AND
t.whse LIKE #whse AND
(CASE
WHEN (#qty IS NULL)
THEN (t.qty = 112)
ELSE (t.qty = #qty)
END)
You can't assign in the case statement.
t.qty = CASE
WHEN (#qty IS NULL) THEN 112
ELSE #qty)
END
I recommend to change the end for clarity:
t.qty=ISNULL(#qty,112)
i have 2 input parameter and i want search with These
CREATE TABLE dbo.tbl_answer
(
an_del INT,
u_username NVARCHAR(50),
u_name NVARCHAR(50) null
)
INSERT dbo.tbl_answer
VALUES(1, 'mohammad', null), (1, 'A13A6C533AF77160FBF2862953FA4530', 'GCV'), (1, 'C', 'GG'), (0, 'AB', 'BB'), (1, 'AC', 'K')
GO
CREATE PROC dbo.SearchAnswers
#Username nvarchar(20),
#Name nvarchar(20)
AS
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1 AND u_username LIKE ISNULL('%' + #Username + '%', u_username)
and u_name LIKE ISNULL('%' + #Name + '%', u_name)
and i run this command EXEC dbo.SearchAnswers 'moha', null but return any data
look at this
Try this :
CREATE PROC dbo.Answers
#Username nvarchar(20),
#Name nvarchar(20)
AS
declare #Name2 nvarchar(20)
set #Name2 = ISNULL(#Name, '00')
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1 AND ( u_username LIKE ISNULL('%' + #Username + '%', u_username)
AND
ISNULL(u_name,'00') LIKE '%' + #Name2 + '%' )
Your problem is that you aren't allowing for u_name to be null in your table. Which it is, on the only record with a u_username containing "moha"
CREATE PROCEDURE dbo.SearchAnswers
#Username nvarchar(20),
#Name nvarchar(20)
AS
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1
AND u_username LIKE ISNULL('%' + #Username + '%', u_username)
AND ISNULL(u_name,'') LIKE ISNULL('%' + #Name + '%', u_name)
You could also have the third conditional explicity test for NULL.
AND ( (u_name is null) or (u_name LIKE ISNULL('%' + #Name + '%', u_name) )
Here you are searching for 2 fields username and name and input parameter is null. Like will not work for null so you have to check for null independently or put some supplementary for that...
CREATE PROC dbo.SearchAnswers
#Username nvarchar(20),
#Name nvarchar(20)
AS
declare #Name2 nvarchar(20)
set #Name2 = ISNULL(#Name, '00')
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1 AND ( u_username LIKE ISNULL('%' + #Username + '%', u_username)
AND
ISNULL(u_name,'00') LIKE '%' + #Name2 + '%' )
SQL Fiddle
hi
i have a problem on converting datetime from character string on createddate and leavestartdate column.....
Table structure createdby varchar(30),createddate datetime, leavetype varchar(30), leavestartdate varchar(30), status varchar(30)
ALTER Procedure [dbo].[sp_SearchLeave]
#createdby varchar(30) = null ,
#createddate DateTime = null ,
#leavetype varchar(30) = null ,
#leavestartdate varchar(30) = null ,
#status varchar(30) = null
As
Begin
if #createddate is not null and Len(#createddate) = 0 set #createddate = null
if #leavetype = 'Select' set #leavetype = null
if #leavestartdate is not null and Len(#leavestartdate) = 0 set #leavestartdate = null
if #status = 'Select' set #status = null
Select leaverequestid,leaveenddate,leavetype,leavestartdate,status
from LeaveRequest
where
(#createdby is null or createdby like '%' + #createdby + '%')
and (#createddate is null or createddate like '%' + #createddate + '%')
and (#leavetype is null or leavetype like '%' + #leavetype + '%')
and (#leavestartdate is null or leavestartdate like '%' + #leavestartdate + '%')
and (#status is null or status like '%' + #status + '%')
End
when i execute this sp as a input like
exec sp_SearchLeave '','','','12/15/2010',''
it displays the error message like
Msg 241, Level 16, State 1, Procedure sp_SearchLeave, Line 26
Conversion failed when converting datetime from character string.
The reason is likely the like statement. You're treating a datetime parameter (#createddate) as a string by appending % to it, which you cannot do.