I have a stored procedure for search screen where I have 5 different filters.
Users can leave the filters empty or have one filter and click on search button.
All the data is coming from database, I am trying to create stored procedure which can exclude columns in where clause if the parameter value is empty string.
#Id as nvarchar(256) = 1
#blnIsinProgress bit = 0
#strStatus varchar(20) = ''
#strName varchar(50) = ''
#strConfirmationNumber varchar(50) = 123
#dtmSubmittedFrom Date = '12/31/9999'
#dtmSubmittedTo Date = '12/31/9999'
as
BEGIN
SELECT *
FROM tblTable
WHERE
(#Id IS NULL OR lngID = #Id) AND
(#blnIsinProgress IS NULL OR blnIsinProgress = #blnIsinProgress) AND
(#strStatus = '' OR strStatus = #strStatus) AND
(#strName= '' OR strName= #strName) AND
(#strConfirmationNumber = '' or #strConfirmationNumber = #strConfirmationNumber )
End
But
Execute spManage 1,0,'','',123
will give me all the results
The problem is this line:
(#strConfirmationNumber = '' or #strConfirmationNumber = #strConfirmationNumber )
The second condition is always true. You have an extra #. So, try this:
(#strConfirmationNumber = '' or #strConfirmationNumber = strConfirmationNumber )
Related
Im having trouble using this code here:
select *
from toadd
where pcode = '' or pcode is null or
brand = '' or brand is null or
description = '' or description is null;
I am trying to return values that doesn't have null or blank value within them columns above.
My problem is: I have coded the query to only return values that are only null or blank values see if it actually works and then Ill use a delete statement based on that query.
But it still returns columns with filled data, even tho I have said not to show any values that are filled in the query.
Not sure why its doing this?
All my columns types are set up as VARCHAR I have mix data with text and numbers.
Here is my table layout:
Table: outerb
Columns:
id int(11) AI PK
pcode varchar(255)
brand varchar(255)
description varchar(255)
size varchar(255)
barcode varchar(255)
This is what it looks like currently
enter image description here
this is my expected result:
enter image description here
change outer or condition to and
select * from toadd where (pcode = '' or pcode is null) and
( brand = '' or brand is null) and
(description = '' or description is null)
If you want rows where all of the tested columns are not empty or not null
select *
from toadd
where !(pcode = '' or pcode is null) AND
!(brand = '' or brand is null) AND
!(description = '' or description is null);
If you want to exclude rows where one or more of the columns are empty or null
select *
from toadd
where !(pcode = '' or pcode is null) OR
!(brand = '' or brand is null) OR
!(description = '' or description is null);
You can get the desired result using the following SQL query
SELECT * FROM `outerb `
WHERE Length(`pcode `) > 0
AND Length(`brand `) >0
AND Length(`description `) > 0
How To append SQL Query in where Clause of Stored Procedure???
IN Stored Prcedure I have defined 1 parameter #ViewType, which accepts 1 of 3 value 'Uploaded','Not Uploaded' and 'ALL'. According to the value of ViewType the condition is applied in where caluse (FileType in below query).
Some Select Query
-> if(#ViewType = 'Uploaded')
WHERE ContractNumber=1234 AND DocumentType='VendorContract' AND ID=54 AND FileType IS NOT NULL
-> if(#ViewType = 'Not Uploaded')
WHERE ContractNumber=1234 AND DocumentType='VendorContract' AND ID=54 AND FileType IS NULL
->
if(#ViewType = 'ALL')
WHERE ContractNumber=1234 AND DocumentType='VendorContract' AND ID=54
You may refactor this logic as a single WHERE clause:
WHERE
(
(#ViewType = 'Uploaded' AND FileType IS NOT NULL) OR
(#ViewType = 'Not Uploaded' AND FileType IS NULL) OR
#ViewType = 'ALL'
) AND
ContractNumber = 1234 AND DocumentType = 'VendorContract' AND ID = 54
I am working on a Stored Procedure that has two input parameters that I need to use COLLATE SQL_Latin1_General_CP1_CI_AS so that I can query non-case sensitive results; however, I would also like to allow for a Show All Option with the inputs. I have not found a way for the Collate to work in a case statement. Note: As a work around I will code with 4 different If statements for the different scenarios of choosing a value and/or show all, but would like something cleaner if possible. Current Code below
Declare
#INCo as bCompany,
#MatBeg as bMatl,
#MatEnd as bMatl,
#Catg as bGroup,
#Model as VarChar(20),
#PatternM as VarChar(20),
#SellOn as VarChar(20),
#PatternS as VarChar(20),
#ShowZero as bYN
set #INCo = '1'
set #MatBeg = '0'
set #MatEnd = 'ZZZZZZZZZZ'
set #Catg = '0'
set #Model = '637'
set #SellOn = 'EBAY'
set #ShowZero = 'Y'
begin
set #PatternM = '%' + #Model + '%';
set #PatternS = '%' + #SellOn + '%';
select i.INCo, i.Material, h.Description, h.Category, c.Description as CatgDesc, i.Booked as Quantity, i.PhyLoc, p.Storage,
i.udModelFit as FitsModel, i.udSellPriceNew as LikeNewSellPrice, i.udSellPriceUsed as UsedSellPrice, i.udSellingOn as SellingOn
from INMT i
left outer join HQMT h on i.MatlGroup=h.MatlGroup and i.Material=h.Material
left outer join HQMC c on h.MatlGroup=c.MatlGroup and h.Category=c.Category
left outer join udPhysicalloc p on i.PhyLoc=p.Physicalloc
where i.INCo = (CASE when #INCo <> 0 then #INCo else i.INCo END)
and i.Material >= #MatBeg and i.Material <= #MatEnd
and c.Category = (CASE when #Catg <> 0 then #Catg else c.Category END)
and i.udModelFit COLLATE SQL_Latin1_General_CP1_CI_AS like #PatternM
and i.udSellingOn COLLATE SQL_Latin1_General_CP1_CI_AS like #PatternS
and i.Booked >= (CASE when #ShowZero = 'N' then 1 else 0 END)
END
This code works works great if I only care about having non-case sensitive results for #Model and #SellOn. However, like the other parameters I have, I would like to include something that allows to show all results for that parameter. Something like:
i.udModelFit = (CASE when #Model <> 'ALL' then COLLATE SQL_Latin1_General_CP1_CI_AS like #PatternM else i.udModelFit END)
So as an example I would like to input #Model = 'ALL' and #SellOn = 'eBay' and results would be any Model with Sell On = EBAY (non-case sensitive)
Update: I was able to modify Where to the following and I am getting the desired results now.
where i.INCo = (CASE when #INCo <> 0 then #INCo else i.INCo END)
and i.Material >= #MatBeg and i.Material <= #MatEnd
and c.Category = (CASE when #Catg <> 0 then #Catg else c.Category END)
and (
(#Model IS NULL or i.udModelFit COLLATE SQL_Latin1_General_CP1_CI_AS like #PatternM)
or ((i.udModelFit like '%' or i.udModelFit IS NULL) and #Model = 'ALL')
)
and (
(#SellOn IS NULL or i.udSellingOn COLLATE SQL_Latin1_General_CP1_CI_AS like #PatternS)
or ((i.udSellingOn like '%' or i.udSellingOn IS NULL) and #SellOn = 'ALL')
)
and i.Booked >= (CASE when #ShowZero = 'N' then 1 else 0 END)
You can use and( (...) or (...) ) e.g.
and (#Model = 'ALL' or i.udModelFit like #PatternM SQL_Latin1_General_CP1_CI_AS)
If you want to toggle different search options based on input, you may want to consider writing your procedure using dynamic sql, and/or adding option (recompile).
Catch-all query reference:
Parameter Sniffing, Embedding, and the RECOMPILE Options - Paul White
Dynamic Search Conditions - Erland Sommarskog
Catch-all queries - Gail Shaw
An Updated "Kitchen Sink" Example - Aaron Bertand
I'm trying to write code in Access 2010 that when the [Validate] button is clicked, it will analyze multiple fields (8 in total) for a value (or no value) and then return a statement (or text) in another field ([AppStatus]) based on whether all of the 8 fields are entered or not. In other words, if any of the fields are null, the [AppStatus] field should populate with the default text of "RE PRE-QUAL". Below is where I started but I can't seem to figure out why it is not working.
Private Sub Validate_Click()
If [PrimarySSN].Value = Null Then
If [PropAddress].Value = Null Then
If [PropCity].Value = Null Then
If [PropState].Value = Null Then
If [PropZipCode].Value = Null Then
If [RequestedLoanAmount].Value = Null Then
If [BorrowerIncome.Value] = Null Then
If [EstHomeValue].Value = Null Then
[AppStatus].Value = "RE PRE-QUAL"
ElseIf [PrimarySSN].Value = Not Null Then
ElseIf [PropAddress].Value = Not Null Then
ElseIf [PropCity].Value = Not Null Then
ElseIf [PropState].Value = Not Null Then
ElseIf [PropZipCode].Value = Not Null Then
ElseIf [RequestedLoanAmount].Value = Not Null Then
ElseIf [BorrowerIncome].Value = Not Null Then
ElseIf [EstHomeValue].Value = Not Null Then
[AppStatus].Value = Null
End If
End If
End If
End If
End If
End If
End If
End Sub
One of the reasons it's not working is because Nothing is ever equal to Null, not even another Null. Another issue is you can't use Not Null in VBA code. (Not Null is valid in Access SQL, but that doesn't help here.) In VBA, use IsNull() to check whether a value is Null.
You want "RE PRE-QUAL" as the value of AppStatus whenever one or more of those other 8 fields is Null (ie IsNull(fieldname.Value) = True). Otherwise, AppStatus will be Null. So you could do something like this ...
If IsNull(Me.PrimarySSN.Value) _
Or IsNull(Me.PropAddress.Value) _
' additional Or conditions for each of next 5 fields
Or IsNull(Me.EstHomeValue.Value) Then
Me.AppStatus.Value = "RE PRE-QUAL"
Else
Me.AppStatus.Value = Null
End If
However that would be a bit unwieldy when extended to all 8 fields.
As an alternative, you could start with a list of the control names, load them into an array, and use a For loop to walk the array checking whether each control value is Null. If any of them is Null, set AppStatus to "RE PRE-QUAL" and break out of the loop.
Dim astrFields() As String
Dim strFieldList As String
Dim varAppStatus As Variant
Dim varField As Variant
strFieldList = "PrimarySSN,PropAddress,PropCity,PropState,PropZipCode," & _
"RequestedLoanAmount,BorrowerIncome,EstHomeValue"
astrFields = Split(strFieldList, ",")
varAppStatus = Null
For Each varField In astrFields
'Debug.Print varField
If IsNull(Me.Controls(varField).Value) = True Then
varAppStatus = "RE PRE-QUAL"
Exit For
End If
Next
Me.AppStatus.Value = varAppStatus
Notice this approach could make maintenance easier. If you ever need to add or remove controls from the list of those which should be examined, or change any of their names, simply edit the strFieldList string.
I think that this is what you need:
If [PrimarySSN].Value = Null Or [PropAddress].Value = Null Or [PropCity].Value = Null Or [PropState].Value = Null Or [PropZipCode].Value = Null Or [RequestedLoanAmount].Value = Null Or [BorrowerIncome.Value] = Null Or [EstHomeValue].Value = Null Then
[AppStatus].Value = "RE PRE-QUAL"
Else
[AppStatus].Value = Null
End If
And also consider this:
Can I do an if inside Where?
or something that allows me to do the checks only if the field is not null (path=null)
SELECT
IF(path IS NOT NULL, concat("/uploads/attachments/",path, "/thumbnails/" , nome), "/uploads/attachments/default/thumbnails/avatar.png") as avatar_mittente
FROM prof_foto
WHERE profilo_id = 15
-- only if path != "/uploads/attachments/default/thumbnails/avatar.png"
AND foto_eliminata = 0 AND foto_profilo = 1
You can try this
SELECT
IF(path IS NOT NULL, concat("/uploads/attachments/",path, "/thumbnails/" , nome), "/uploads/attachments/default/thumbnails/avatar.png") as avatar_mittente
FROM prof_foto
WHERE profilo_id = 15
AND IF( path != "/uploads/attachments/default/thumbnails/avatar.png",
foto_eliminata = 0 AND foto_profilo = 1,
foto_eliminata like '%' AND foto_profilo like '%'
)
You can just use binary logic for this:
SELECT * FROM TABLE WHERE A
(if b then also where C)
Becomes
SELECT * FROM TABLE WHERE A
AND (!b OR C)
In your case:
SELECT
IF(path IS NOT NULL, concat("/uploads/attachments/",path, "/thumbnails/" , nome), "/uploads/attachments/default/thumbnails/avatar.png") as avatar_mittente
FROM prof_foto
WHERE profilo_id = 15
AND (path = "/uploads/attachments/default/thumbnails/avatar.png" OR foto_eliminata = 0 AND foto_profilo = 1))
Yes, you can use IF() wherever a value is expected, even though most of the time it is not the best route to take.
WHERE IF(path IS NULL, portfolio_id = 15, TRUE)
But prefer:
WHERE path IS NULL OR portfolio_id = 15
(notice you cannot compare with NULL, [anything] = NULL is always FALSE)