Apply query criteria based on parameters - database

I need to run a query in a MS Access Database providing some parameters from a form. Imagine the next example:
I have a form which contains:
CheckBox1 and Text1
CheckBox2 and Text2
Button (to run query)
Now imagine a query with two fields: ID, NAME.
I want to filter ID by Text1 only when CheckBox1 is enabled. If not, I want the query not to filter ID in any way (as if the 'query' input was empty).
In the same way, I want to filter NAME by Text2 only when CheckBox2 is enabled. If not, I want the query not to filter NAME in any way (just like ID before).
I've tried so many things for a couple of days and have sniffed tons of internet pages and still don't come up with a solution.

You can use a SQL query such as the following:
select * from YourTable t
where
([Forms]![YourForm]![CheckBox1] = False or t.ID = [Forms]![YourForm]![Text1]) and
([Forms]![YourForm]![CheckBox2] = False or t.NAME = [Forms]![YourForm]![Text2])
(Change YourTable to the name of your table and YourForm to the name of your form; t is merely an alias so that you only have to change the table name in one place in the code).

Related

how to view object attribute based on sql query?

i have a view object that contains the following attributes
studentId
courseId
enrollDate
notes
and I have added 2 attributes, which are
studentName
courseName
and I want to select their values from another table(student,course) based on an SQL query.
i have tried to make a default value :SQL
and wrote the following query
select Course.courseName from Course where StudentCourse.CourseId = Course.id
but it didn't work.
You can get their values from an SQL query. This may help. Or this. Or this.

Access to SQL Server - query results from a table as another tables query columns

I am taking user input from a series of combo boxes in a MS Access form, which might not all be chosen, so some will be "". But for the responses that are not "", I want to query those columns for the table the user has selected.
For example, this is my utopian solution which I'm I have no idea how to accomplish other than building a query for every possible combination and calling a procedure for that query:
SELECT **NON "" COMBOBOX CHOICES**
FROM T1
You can talk about the combobox field in the following syntax:
Forms![myForm]![myComboBox1Name]
The above returns the text from that box, either "" or a string they chose from the options. So in short, I was wondering if I inserted the valid non "" strings from those combo boxes into a table, then somehow used a SELECT statement on the table we could use the rows returned as the fields I want to query, example:
SELECT (SELECT * FROM ValidTable)
FROM T1
If the resource from the following link were successful, https://www.google.com/amp/s/blog.sqlauthority.com/2012/10/27/sql-server-storing-variable-values-in-temporary-array-or-temporary-list/amp/

Search for a value in two columns in two different tables with SQL?

I want a code to search for a value in two columns in two different SQL tables ,
a = raw_input('Enter name here')
cur.execute('SELECT phone FROM participants')
b = cur.fetchall()
if a in b:
print "The name is already exist"
Here I searched in on table (participants). What should I do to search in two tables?
Assuming you are asking for SQL statement, you need to just use select from two tables instead of one. To keep everything in single statement, you can use UNION as described eg. here: https://www.w3schools.com/sql/sql_union.asp
Let's assume you have second table, named friends with phone field also there.
Then, your SQL will be like this:
SELECT phone FROM participants where name = <input name here>
UNION
SELECT phone FROM friends where name = <input name here>
You can add sort at the end, if this is relevant for your case.
This you can also search more than one column in each table, by adding "or" clause, like this:
SELECT phone FROM participants where name = <your input here> or lastname = <your input here>
UNION
SELECT phone FROM friends where name = <your input here> or lastname = <your input here>
Of course, you have to replace with proper search string.
BTW, the code you provided is not searching anything - it is just dumping all phones from the table into "b" variable, which may be very inefficient especially when the table grows large. I strongly suggest to search via SQL and then present your output from script.

TSQL query to filter directory

I'm trying to create a business directory in which I'm using the following query to pull data from 2 tables that contain the business info.
select *
from BND_Listing
left join BND_ListingCategories on BND_Listing.CatID = BND_ListingCategories.CatID
order by Company asc
I have a form that has 3 dropdowns I'm using to filter the above query using "Filters" that really are just components I need to add to my query above that will listen to query string values passed in by the form.
On submit of my form I'm redirecting back to the same URL but adding the following in my URL based on values selected from 3 dropdown fields.
filter-Category=[Category]&filter-City=[City]&filter-State=[State]
I've got this working correctly but am having difficulties when no value is passed into my URL. This happens when a user filters only by 1 of the 3 possible fields. To fix this I'm thinking I can create an "All" value that would be like filter-State=ALL
How can I update my query to pull data to listen for these filters in the query-string?
Any insight, examples really appreciated.
Hope I make sense I'm still new to programming.
The following query returns 0 results until all filters are set. If only 1 filter is set it crashed my application.
select *
from BND_Listing
where
(Category = '[querystring:filter-Category]'
or '[querystring:filter-Category]'='All')
and
(City = '[querystring:filter-City]'
or '[querystring:filter-City]'='All')
and
(State = '[querystring:filter-State]'
or '[querystring:filter-State]'='All')
UPDATE:
Thanks for all the input everyone.
I've tried this simplified query in SQL Server Management Studio to test.
SELECT *
FROM BND_listing
WHERE city = IsNull('Trinity', city)
It returns no results even though 'Trinity' is in fact a city in one of my records in the BND_Listing table.
I understand the ALL would add more filters but this basic query is still not pulling anything?
UPDATE 2:
On page load where I have not pressed the sort button and there are no query string values passed yet. If I want my grid to load ALL table records should I use a UNION command for my basic query.
select *
from BND_Listing
Plus the more complex query used for filtering the results? So far all query examples below pull in nothing from my grid because of the WHERE statement.
Are you limited to just a select query that has to be placed in the plug-in? If not, I would create a stored procedure and read up on dynamic SQL. Dynamic SQL would allow you to dynamically generate and execute a completely different query based on whatever conditions you specify. With dynamic SQL, you could also dynamically generate the entire predicate instead of having to hard code each condition.
Another (less efficient) alternative would be to use LIKE instead of = in your predicate. For example:
SELECT *
FROM BND_Listing
WHERE Category LIKE CASE
WHEN [querystring:filter-Category] = 'All' THEN '%'
ELSE '[querystring:filter-Category]'
END
AND City LIKE CASE
WHEN [querystring:filter-City] = 'All' THEN '%'
ELSE '[querystring:filter-City]'
END
AND State LIKE CASE
WHEN [querystring:filter-State] = 'All' THEN '%'
ELSE '[querystring:filter-State]'
END
Assuming you want to search for 'All' for a given category when no filter is present, you can just treat an empty filter as meaning all:
SELECT *
FROM BND_Listing
WHERE (Category = '[querystring:filter-Category]' OR
'[querystring:filter-Category]' = 'All' OR
COALESCE([querystring:filter-Category], '') = '') AND
(City = ... )
...
Perhaps you could try something like this.
SELECT *
FROM BND_listing
WHERE category = IsNull('[querystring:filter-Category]', category)
AND city = IsNull('[querystring:filter-City]', city)
AND state = IsNull('[querystring:filter-State]', state)
This functionality will check for an active filter if present and compare the appropriate field to ensure it matches.
In the case the filter has not been set it will compare the field to itself so it will always return a true result.
When you want all the records when the input is NULL then handle it using IS NULL.
SELECT *
FROM BND_listing
WHERE (category = '[querystring:filter-Category]' OR [querystring:filter-Category]' is NULL)
AND (city = '[querystring:filter-City]' OR '[querystring:filter-City]' IS NULL)
AND (state ='[querystring:filter-State]' OR '[querystring:filter-State]' IS NULL)
Note : This method will use any INDEX present on Category or city or state where as ISNULL or COALESCE method will restrict the optimizer from using INDEX

Salesforce - Apex - query accounts based on Activity History

Hey Salesforce experts,
I have a question on query account information efficiently. I would like to query accounts based on the updates in an activityHistory object. The problem I'm getting is that all the accounts are being retrieved no matter if there's "complete" activeHistory or not. So, Is there a way I can write this query to retrieve only accounts with activeHistory that has status="complete" and Type_for_reporting='QRC'?
List<Account> AccountsWithActivityHistories = [
SELECT
Id
,Name
,( SELECT
ActivityDate
,ActivityType
,Type_for_Reporting__c
,Description
,CreatedBy.Name
,Status
,WhatId
FROM ActivityHistories
WHERE Status ='complete' and Type_for_Reporting__c = 'QRC'
)
FROM Account
];
You have a WHERE clause on the histories but you still miss one on the Account level.
For example this would return only Accounts that have Contacts:
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact) // try with NOT IN too
With Activities it's trickier because they don't like to be used in WHERE in that way.
http://www.salesforce.com/us/developer/docs/officetoolkit/Content/sforce_api_calls_soql_select.htm
The following objects are not currently supported in subqueries:
ActivityHistory
Attachments
Event
EventAttendee
Note
OpenActivity
Tags (AccountTag, ContactTag, and all other tag objects)
Task
Additionally the fine print at the bottom of ActivityHistory definition is also a bit discouraging.
The following restrictions on users who don’t have “View All Data” permission help prevent performance issues:
In the main clause of the relationship query, you can reference only
one record. For example, you can’t filter on all records where the
account name starts with ‘A’; instead, you must reference a single
account record.
You can’t use WHERE clauses.
You must specify a limit of 499 or fewer on the number of rows returned in the list.
You must sort on ActivityDate in ascending order and LastModifiedDate in descending order; you can display nulls last. For
example: ORDER BY ActivityDate ASC NULLS LAST, LastModifiedDate DESC.
Looks like you will need multiple queries. Go for Task (or Event, depending for which the custom field is visible), compose a set of AccountIds and then query the Accounts?
Or you can manually filter through list from your original query, copying accounts to helper list:
List<Account> finalResults = new List<Account>();
for(Account a : [SELECT...]){
if(!a.ActivityHistories.isEmpty()){
finalResults.add(a);
}
}

Resources