How do I use a Parameter form to select whether or not I want null values? - sql

I am working on a database that my school uses for student recruitment. I want to include an option on the parameter form used to generate a students contact information that allows the user to select whether or not to include "applied" students in that contact list. I am currently trying to do that by using a select query that pulls data based on whether or not the "IdNumber" field is null. When I run the attached SQL, it doesn't pull any data at all. Any help would be appreciated!
SELECT InterestCards.NotStudentID, InterestCards.Email, InterestCards.YearOfGraduation,
InterestCards.SourceTwoLocation, InterestCards.FirstName, InterestCards.LastName,
InterestCards.Program, InterestCards.Inactive, InterestCards.IDNumber
FROM InterestCards
WHERE (((InterestCards.Email)<>"no email")
AND ((InterestCards.YearOfGraduation) Like [Forms]![MassCommunicationTool]![GradYear] & "*")
AND ((InterestCards.SourceTwoLocation) Like [Forms]![MassCommunicationTool]![FairName] & "*")
AND ((InterestCards.Inactive)=No)
AND ((InterestCards.IDNumber)=Switch([Forms]![MassCommunicationTool]![IncludeApplied]=0,Null,[forms]![MassCommunicationTool]![IncludeApplied]=(-1),([InterestCards].[IDNumber]) Is Not Null Or ([InterestCards].[IDNumber]) Is Null))
AND ((InterestCards.HighSchool) Like [Forms]![MassCommunicationTool]![HighSchool] & "*")
AND ((InterestCards.SourceThreeType) Like [Forms]![MassCommunicationTool]![SelectTerm] & "*")
AND ((InterestCards.DateEntered) Between Nz([Forms]![MassCommunicationTool]![StartDate],#1/1/1900#) And Nz([Forms]![MassCommunicationTool]![EndDate],#1/1/2199#)));

Operators cannot be dynamic in a query object. Cannot be selected via a conditional expression. However, parameters can be dynamic. Suggest you construct a field with an expression that handles the nulls to return either of 2 values:
IIf([IDNumber] Is Null, "XXXX", "AAAA") AS Grp
Then to select either the Null or not Null records, apply conditional parameter to that field:
Grp = IIf([Forms]![MassCommunicationTool]![IncludeApplied]=0, "XXXX", "AAAA")
I've never used dynamic parameterized queries. I prefer VBA to construct filter criteria and apply to form or report.

Related

Dynamic where condition PostgreSQL

I am building a CRUD application that allows the user to input some search criteria and get the documents corresponding to those criteria. Unfortunately i have some difficulties in creating a query in postgres that uses different conditions in the where part, based on the input sent by the user.
For example if the user set as search criteria only the document number the query would be defined like this:
select * from document where document_num = "value1"
On the other hand if the user gave two criteria the query would be set up like this:
select * from document where document_num = "value1" and reg_date = "value2"
How can i set up a query that is valid for all the cases? Looking in other threads i saw as a possible solution using coalesce in the where part:
document_num = coalesce("value1", document_num)
The problem with this approach is that when no value is provided postgres converts the condition to document_num IS NOT NULL which is not what i need (my goal is to set the condition to always true).
Thanks in advance
So the solution by #D-shih will work if you have a default value and you can also use COALESCE as below.
SELECT *
FROM document
WHERE document_num = COALESCE("value1", default_value)
AND reg_date = COALESCE("value2", default_value);
If you don't have default values then you can create your query using CASE WHEN(here I am supposing you have some variables from which you will determine which conditions to apply like when to apply document_num or when to apply reg_date or when to apply both). Giving a little example below.
SELECT *
FROM document
WHERE
(
CASE
WHEN "value1" IS NOT NULL THEN document_num = "value1"
ELSE TRUE
END
)
AND (
CASE
WHEN "value2" IS NOT NULL THEN reg_date = "value2"
ELSE TRUE
END
)
You can read more how to use CASE WHEN here.
If I understand correctly, you can try to pass the user input value by parameter.
parameter default value might design that the user can't pass if the user didn't want to use the parameter it will use the default value.
we can use OR to judge whether use parameter otherwise ignores that.
SELECT *
FROM document
WHERE (document_num = :value1 OR :value1 = [default value])
AND (reg_date = :value2 OR :value2 = [default value])

How to concatenate date variables to create between in where condition

While I am trying to set my value to between the user given start date and end date for a query, I am running into a run-time error 3071 (The expression is typed incorrectly or it is too complex)
This is being used to pass a user given variable from a form to a query
Please see below
WHERE (
IIf([Forms]![Find]![Entity]<>"",DB.Entity=[Forms]![Find]![Entity],"*")
AND IIf([Forms]![Find]![AEPS]<>"",DB.AEPSProgram=[Forms]![Find]![AEPS],"*")
AND IIf([Forms]![Find]![DeliveryType]<>"",DB.DeliveryType=[Forms]![Find]![DeliveryType],"*")
AND IIf([Forms]![Find]![ReportingYear] is not Null,DB.ReportingYear=[Forms]![Find]![ReportingYear],"*")
AND IIf([Forms]![Find]![Price] is not Null,DB.Price=[Forms]![Find]![Price],"*")
AND IIf([Forms]![Find]![Volume]is not Null,DB.Volume=[Forms]![Find]![Volume],"*")
AND IIf([Forms]![Find]![sDate] is not Null AND [Forms]![Find]![eDate] is not Null,DB.TransactionDate= ">" & [Forms]![Find]![sdate] & " and <" & [Forms]![Find]![edate],"*")
);
If I set it equal to one of the dates it works as expected. I assume I am missing something with how I am joining the dates
Thank you
This (for the date field only) works:
WHERE (((DB.TransactionDate)>[Forms]![Find]![sdate] And (DB.TransactionDate)<[Forms]![Find]![edate])) OR ((([Forms]![Find]![sDate]+[Forms]![Find]![eDate]) Is Null));
Don't use *, it is for use with Like.
Consider assigning NULL condition to corresponding column via NZ() which sets column equal to itself and so avoids filtering any rows by that respective condition. Asterisks alone does not evaluate to a boolean condition unless using LIKE operator.
WHERE DB.Entity = NZ([Forms]![Find]![Entity], DBEntity)
AND DB.AEPSProgram = NZ([Forms]![Find]![AEPS], DB.AEPSProgram)
AND DB.DeliveryType = NZ([Forms]![Find]![DeliveryType], DB.DeliveryType)
AND DB.ReportingYear = NZ([Forms]![Find]![ReportingYear], DB.ReportingYear)
AND DB.Price = NZ([Forms]![Find]![Price], DB.Price)
AND DB.Volume = NZ([Forms]![Find]![Volume], DB.Volume)
AND DB.TransactionDate >= NZ([Forms]![Find]![sdate], DB.TransactionDate)
AND DB.TransactionDate <= NZ([Forms]![Find]![edate], DB.TransactionDate)
;

convert text field to a date/time field in access query not working

I'm working with a access database and vb6. My table has a field named "InvoiceDate" which is a text field. I'm not allowed to make database modifications. So I guess my only option is to change the text field into a date/time field in my query. I found several methods to do so. They are as follows.
Format(InvoiceDate, "yyyy/mm/dd")
(DateSerial(Left(InvoiceDate,4),Mid(InvoiceDate,5,2),Right(InvoiceDate,2))
Between #2015/01/01# And #2016/01/01#))
DateValue(InvoiceDate, "yyyy/mm/dd")
CDate(InvoiceDate, "yyyy/mm/dd")
But those 4 methods didn't work. I can't figure out this.
The query I'm using as follows
SELECT Invoice.InvoiceDate, InvoicedProduct.InvoiceType, Invoice.InvoiceStatus,
Invoice.RetailerID, Invoice.DailySalesID, Invoice.RepID,
InvoicedProduct.Quantity, InvoicedProduct.UnitRate,
InvoicedProduct.TotalItemValue
FROM Invoice
INNER JOIN InvoicedProduct
ON (Invoice.DailySalesID = InvoicedProduct.DailySalesID)
AND (Invoice.RepID = InvoicedProduct.RepID)
AND (Invoice.InvoiceID = InvoicedProduct.InvoiceID)
WHERE (((InvoicedProduct.ProductID)='9010001174130.4')
AND (DateValue(Invoice.InvoiceDate) Between #2015/01/01# And #2016/01/01#))
GROUP BY Invoice.InvoiceDate, InvoicedProduct.InvoiceType, Invoice.InvoiceStatus,
Invoice.RetailerID, Invoice.DailySalesID, Invoice.RepID,
InvoicedProduct.Quantity, InvoicedProduct.UnitRate,
InvoicedProduct.TotalItemValue
HAVING (((InvoicedProduct.InvoiceType)='Invoice' OR (InvoicedProduct.InvoiceType)='Sound')
AND ((Invoice.InvoiceStatus)='VALID'))
ORDER BY Invoice.InvoiceDate;
This gives me the error "Data Type mismatch in criteria expression"
Following two types are include in my InvoiceDate Field
2016/01/04 10:00: AM and 2016/01/20 08:25 PM
The only difference is the colon after the time
Please help.
Thank you.
Your criteria:
DateValue(Invoice.InvoiceDate) Between #2015/01/01# And #2016/01/01#
is correct, so the error message indicates, that one or more of your text dates in InvoiceDate don't represent a valid date, like 2015-06-31 or Null.
Run a query to check this:
Select *, IsDate(InvoiceDate) As ValidDate From Invoice
and see if any of the values of ValidDate are False.
To ignore the extra colon:
DateValue(Replace(Invoice.InvoiceDate, ": ", " ")) Between #2015/01/01# And #2016/01/01#

Handle null values within SQL IN clause

I have following sql query in my hbm file. The SCHEMA, A and B are schema and two tables.
select
*
from SCHEMA.A os
inner join SCHEMA.B o
on o.ORGANIZATION_ID = os.ORGANIZATION_ID
where
case
when (:pass = 'N' and os.ORG_ID in (:orgIdList)) then 1
when (:pass = 'Y') then 1
end = 1
and (os.ORG_SYNONYM like :orgSynonym or :orgSynonym is null)
This is a pretty simple query. I had to use the case - when to handle the null value of "orgIdList" parameter(when null is passed to sql IN it gives error). Below is the relevant java code which sets the parameter.
if (_orgSynonym.getOrgIdList().isEmpty()) {
query.setString("orgIdList", "pass");
query.setString("pass", "Y");
} else {
query.setString("pass", "N");
query.setParameterList("orgIdList", _orgSynonym.getOrgIdList());
}
This works and give me the expected output. But I would like to know if there is a better way to handle this situation(orgIdList sometimes become null).
There must be at least one element in the comma separated list that defines the set of values for the IN expression.
In other words, regardless of Hibernate's ability to parse the query and to pass an IN(), regardless of the support of this syntax by particular databases (PosgreSQL doesn't according to the Jira issue), Best practice is use a dynamic query here if you want your code to be portable (and I usually prefer to use the Criteria API for dynamic queries).
If not need some other work around like what you have done.
or wrap the list from custom list et.

How to create if and or parameter statement in Crystal Reports

Apologies for posting a new question but I just can't think how to search for this question.
I'm creating a Crystal Report with multiple parameters and at the moment each one is connected by an ‘AND’ in the Report > Selection Formulas part of the report (not the SQL command part).
I haven’t fully authored the report and it contains lots of arrays to deal with multiple text values and wildcard searches but I think my question should be more around logic than the technical functions.
So…
Parameters are for things like product code, date range, country, batch number etc.
Currently the parameters I’m concerned with are Faults and keyword searches for complaints against products.
(Query 1) If all other parameters are set to default I can enter Fault Combination = ‘Assembly – Code’ and that gives me 17 records.
(Query 2) Entering keyword = ‘%unit%’ gives me 55 records.
The 2 parameters are connected by an AND so if I use Fault Combination = ‘Assembly – Code’ and Keyword = ‘%unit%’ then I get 12 records. If the connect the 2 queries with OR then I get 12 records.
If I compare the unique records, in excel, between query 1 & 2 then there are 60 records with Fault Combination = ‘Assembly – Code’ OR keyword = ‘%unit%.
How can write the parameter formula to get the 60 unique records with one query?
Many thanks!
Gareth
Edit - Code Added
This is the segment i'm concerned with. The arrays are defined earlier in the statement and the '*' & '%' parts of the query below are just to deal with the different wildcard operators between SQL and Crystal. There are a lot of other parameters but these 3 are the only ones that need the OR kind or connection.
Hope that helps!
(IF "%" LIKE array_fn2
THEN ((ISNULL({Command.FaultNoun})=TRUE) OR ({Command.FaultNoun} LIKE '*'))
ELSE IF {Command.RecordType} = 'Complaint'
THEN ({Command.FaultNoun} like array_fn2)
ELSE ((ISNULL({Command.FaultNoun})=TRUE) OR ({Command.FaultNoun} LIKE '*'))) AND
(IF "%" LIKE array_fa2
THEN ((ISNULL({Command.FaultAdjective})=TRUE) OR ({Command.FaultAdjective} LIKE '*'))
ELSE IF {Command.RecordType} = 'Complaint'
THEN ({Command.FaultAdjective} like array_fa2)
ELSE ((ISNULL({Command.FaultAdjective})=TRUE) OR ({Command.FaultAdjective} LIKE '*'))) AND
(IF ("%" LIKE array_k2) OR ({Command.RecordType} = 'Sale')
THEN ((ISNULL({Command.ActualStatements})=TRUE) OR ({Command.ActualStatements} LIKE '*')
OR (ISNULL({Command.ResultsAnalysis})=TRUE) OR ({Command.ResultsAnalysis} LIKE '*')
OR (ISNULL({Command.Observation})= TRUE) OR ({Command.Observation} LIKE '*'))
ELSE
({Command.ActualStatements} like array_k2) OR
({Command.ResultsAnalysis} like array_k2) OR
({Command.Observation} like array_k2))