Change SSS Report Condition based on report Parameter - reporting-services

I spent some time looking around at other questions on the board, but didn't find anything similar so here it goes:
I have a report that runs up against the limits of CRM 2011 online in regards to the max number of characters in a Fetch Query. I would like to have a drop box that has an option for "All Contacts" or "Select up to Five Contacts" to avoid that issue.
What I would like to do is remove the condition from the Fetch statement if the "All Contacts" option is selected, and include the condition only if the select up to five is chosen.
How would I go about doing this?
Let me know if you have any further questions.
Nick

You can build your SQL using custom code because the SQL itself can be a string expression that you build manually. Let's say your SQL looks like this at the moment:
SELECT ThisField, ThatField
FROM Contacts
WHERE ContactId IN #Contacts
Let's change that to a string expression that builds the SQL:
="SELECT ThisField, ThatField "
& "FROM Contacts "
& "WHERE ContactId IN #Contacts "
Now we need to pull the #Contacts parameter apart and only select by ContactId when there are five or less contacts selected:
Function ContactsSQL(ByVal parameter As Parameter) AS String
Dim Result As String
Result = ""
If parameter.IsMultiValue Then
If parameter.Count <= 5 Then
Result = "WHERE ContactId IN ("
For i As integer = 0 To parameter.Count-1
Result = Result + CStr(parameter.Value(i)) + ", "
Next
Result = Left(Result, Result.Length - 2) + ") "
End If
End If
Return Result
End Function
This function builds the SQL WHERE clause to select the contacts only if five or less have been selected, otherwise it passes back an empty string. Now we use this function in our SQL expression:
="SELECT ThisField, ThatField "
& "FROM Contacts "
& Code.ContactsSQL(Parameters!Contacts)
Note that you are passing the Contacts parameter object here, not the Value property. We access the Value property in the custom code function.

Related

Enter parameter value but I've already included one in the query

I've got a SQL query in my VB6 project that is performing a three-way INNER JOIN in an Ms-Access database.
The VB6 query is:
SQL = "SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference" & _
" FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)" & _
" INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber" & _
" WHERE (([WHERE popsLines].[stockCode]=" & sqlString(m_sStockCode) & "));"
This wasn't working, it returned an error saying
No value given for one or more required parameters
So then next thing I did was copy the value in the SQL variable and paste it into an Access query, with the value of the m_sStockCode parameter.
SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference
FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)
INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber WHERE (([WHERE popsLines].[stockCode]="010010003"));
When executing this, it said
Enter Parameter Value: WHERE popsLines.StockCode
Why isn't it accepting the query as it is?
I've also tried changing there WHEREclause to
(( WHERE [popsLines].[stockCode]="010010003"));
but got
Syntax error (missing operator) in query expression '((WHERE [popsLines].[stockCode]="010010003"))'
The last part - your WHERE clause - is garbled. It should read:
.. WHERE ([popsLines].[stockCode]='010010003');

Filtering a MS-Access recordset based on records in another recordset

I have two tables (lets call them Parameters 1 and 2) which both have a many-many relationship with a third table (Options). I need to group the third table records into three groups:
Those exclusively related to [specific Parameter 1 record],
Those exclusively related to [specific Parameter 2 record] and
Those related to both [specific Parameter 1 record] and [specific Parameter
2 record].
I can ignore Option records not related to either of them.
I need to be able to specify which Parameter 1 and 2 records apply in a form (using combo boxes), and have VBA juggle the three lists in the background, updating them as the Option records they contain are "used" elsewhere in the form (with check boxes).
At the risk of asking a bad question I'll submit the code I have - even though it's not a code that fails, just the framework for one that isn't even finished enough to debug yet. I simply haven't got the tools to complete it, as I don't know what methods/properties of what things to use to do it, and can't seem to find the answers in my own research thus far. Comments directing me to other resources will be appreciated, even if you don't have an answer that you're sure is best practice.
Function SetOptions()
If IsNull(cmbParam1) Or IsNull(cmbParam2) Then
MsgBox "You must select both an Param1 and a Param2!", vbCritical, "Wait!"
Exit Function
End If
'Recordsets of allowed Options
Dim Param1Opt, Param2Opt, OverlapOpt
'create recordset of tblOption.Option(s) referenced in qryPr1Opt with Param1 from cmbParam1
Param1Opt = CurrentDb.OpenRecordset("SELECT tblPr1Opt.Option FROM tblPr1Opt " &_
"WHERE Param1 = '" & cmbParam1 & "';")
'create recordset of tblOption.Option(s) referenced in qryPr2Opt with Param2 from cmbParam2
Param2Opt = CurrentDb.OpenRecordset("SELECT tblPr2Opt.Option FROM tblPr2Opt " &_
"WHERE Param2 = '" & cmbParam2 & "';")
'create recordset of tblOption.Option(s) in qryOptOvrlp with Param2 and Param1 from form
OverlapOpt = CurrentDb.OpenRecordset("SELECT qryOptOvrlp.Option FROM qryOptOvrlp " &_
"WHERE Param1 = '" & cmbParam1 & "' AND Param2 = '" & cmbParam2 & "';")
OverlapNum = Param1Num + Param2Num
'Steps remaining:
'1. Get Param1Opt and Param2Opt to only include Options not in overlap
For Each oOpt In OverlapOpt
For Each aOpt In Param1Opt
If aOpt.Value = oOpt.Value Then
'filter this record out of Param1Opt
End If
Next aOpt
For Each gOpt In Param2Opt
If gOpt.Value = oOpt.Value Then
'filter this record out of Param2Opt
End If
Next gOpt
Next oOpt
'2. Get the data in Param1Opt, Param2Opt and OverlapOpt, as well as their
'corresponding Nums to be accessible/editable in other functions/subs
End Function
You can reference the values of controls in SQL statements run in the context of Access, using the following syntax:
Forms!FormName!ControlName
or using square brackets if needed:
Forms![Form Name]!ControlName
Therefore, instead of opening multiple recordsets, you can express each of your points as a single SQL statement with joined tables. You can then either set the RowSource of a combobox or listbox to the statement (if you are only using the statement in one place); or you can save the statement as an Access query, and use the query name as the RowSource (if you need the statement in multiple places).
Given the following schema:
and two comboboxes: cmbParam1 and cmbParam2 on a form named Form1, you can use SQL statements as follows:
1. Records from Options which match tblPr1Opt but have no match in tblPr2Opt
SELECT DISTINCTROW Options.Option
FROM (Options
INNER JOIN tblPr1Opt ON Options.Option = tblPr1Opt.Option)
LEFT JOIN tblPr2Opt ON Options.Option = tblPr2Opt.Option
WHERE tblPr2Opt.Option IS NULL
AND tblPr1Opt.Param1 = Forms!Form1!cmbParam1
Or using the query designer (note the arrow head next to tblPr2Opt; this indicates a left join):
2. Records from Options which match tblPr2Opt but have no match in tblPr1Opt:
SELECT DISTINCTROW Options.Option
FROM (Options
INNER JOIN tblPr2Opt ON Options.Option = tblPr2Opt.Option)
LEFT JOIN tblPr1Opt ON Options.Option = tblPr1Opt.Option
WHERE tblPr1Opt.Option IS NuLL
AND tblPr2Opt.Param2 = Forms!Form1!cmbParam2;
or in the query designer:
3. Records from Options which match on both:
SELECT Options.Option
FROM (Options
INNER JOIN tblPr1Opt ON Options.Option = tblPr1Opt.Option)
INNER JOIN tblPr2Opt ON Options.Option = tblPr2Opt.Option
WHERE tblPr1Opt.Param1 = Forms!Form1!cmbParam1
AND tblPr2Opt.Param2 = Forms!Form1!cmbParam2
Or in the query designer:

How do I get the value of a Form into an SQL query?

I am trying to get an Access SQL query that does this (semi-pseudocode below)
UPDATE SignIn SET SignIn.Complete=True, CompletedBy=(Select [FirstName] & " " & [LastName] AS EmployeeName From UserList where POid = Forms!HiddenUserCheck!txtPOid), CompletedDateTime=Now()
So after the query would run, the data in the database would look like
Complete EmployeeName CompletedDateTime
True John Smith 3/23/2017 8:34:10 AM
THe update query doesn't work because of syntax and not sure how to fix it.
The exact error message is
Invalid Memo, OLE, or HyperLink Object in subquery '[FirstName] & " "
& [LastName]'.
The query could be throwing a fit because of the Double Exclamation marks. Instead of
Forms!HiddenUserCheck!txtPOid
Try
Forms!HiddenUserCheck.txtPOid
You also have an extra ) at the end of your WHERE Statment
OK, then your issue may be that the subquery may return more than one record:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
(Select First([FirstName] & " " & [LastName]) AS EmployeeName
From UserList
Where POid = Forms!HiddenUserCheck!txtPOid),
CompletedDateTime = Now()
If your name fields are Memo/LongText fields, that may be the source of the error. If so, try:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
(Select First(Left([FirstName], 255) & " " & Left([LastName], 255)) AS EmployeeName
From UserList
Where POid = Forms!HiddenUserCheck!txtPOid),
CompletedDateTime = Now()
Edit.
You may try using DLookup for the subquery:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
DLookup("[FirstName] & " " & [LastName]", "UserList", "POid = " & Forms!HiddenUserCheck!txtPOid & ""),
CompletedDateTime = Now()

combobox rowsource based on forms record source (distinct) field

I have a form record source set to a elaborate SQL select statement. That is working fine. If it helps to know, the form layout is Tabular. Here is an example of the data:
order carrier billto employee
1 smgd horm chrnic
2 axxm sele chrnic
3 smgd horm redned
4 mcta cron greand
5 mcta cron greand
Its basically unbilled order entries. I want a combo box to show distinct employee names (chrnic, redned, greand) based on the current records showing. I will be coding it to filter the form. Seems simple, but I am having trouble
Things I have tried:
Tried setting rowsource to me.recordsource, but get an
It appears that I would need to parse & edit that string
I copied the complex query & put as combo box record source & that worked to filter the form, so I know that filter logic is correct. I just want it to be dynamic so we only have to change SQL statement in one place if needed
"I have a form record source set to a elaborate SQL select statement."
Save that query as a named QueryDef. I will pretend you chose qryRecordSource as the name.
"I want a combo box to show distinct employee names ... based on the current records"
For the combo box row source use ...
SELECT DISTINCT employee
FROM qryRecordSource
ORDER BY 1;
And then to filter the form based on the combo selection, add a command button, cmdApplyFilter, and use this in its click event procedure ...
Me.Filter = "[employee] = '" & Me.YourComboName.Value & "'"
Me.FilterOn = True
If the employee names can include an apostrophe, use this for the Filter expression ...
Me.Filter = "[employee] = '" & _
Replace(Me.YourComboName.Value, "'", "''") & "'"
If you want to include a combo row to clear the filter, use a UNION query as the combo row source ...
SELECT "*** ALL ***" AS employee
FROM Dual
UNION
SELECT employee
FROM qryRecordSource
ORDER BY 1;
... where Dual is any table or query which returns just one row. Then in the command button click event you can do ...
If Me.YourComboName.Value = "*** ALL ***" Or _
IsNull(Me.YourComboName.Value) Then
Me.Filter = vbNullString
Me.FilterOn = False
Else
Me.Filter = "[employee] = '" & Me.YourComboName.Value & "'"
Me.FilterOn = True
End If
And actually you wouldn't even need the command button. You could set the Filter from the combo's AfterUpdate event.

SQL Select statement wont return char fields only numeric fields

I have been racking my brain over this all day today.
I have the following ASP code that uses a Request.Querystring input from a dropdown box
to launch a select statement. The querystrinch does show in the ?= URL but will only work on
columns in the Microsoft SQL DB that are numeric. I cant lookup names or simple 3 character fields.
CODE:
If Request.QueryString("m") > 0 Then
filterID = Request.QueryString("m")
filterColmn = "imDegree"
Else filterID = 0
End If
If filterID > 0 Then
SQlQuery = "SELECT * FROM v_InternImport WHERE iID IN (SELECT iID FROM v_InternImport WHERE " & filterColmn & " = " & filterID & ")"
End If
End If
I understand that this select statement as a sub select stament in it but I cant even get a staight reuturn from my DB. The select statement references the same view that populates the main asp page that loads before and the shows fine?
When you pass a string to SQL Server, you need to surround it with single quotes.
When you pass a number, you don't use the quotes.
So, when you say (summarizing)
SELECT * FROM table WHERE filterColumn = filterID
you should be sending a number.
To match a string:
SELECT * FROM table WHERE filterColumn = 'filterID'
This assumes that you have solved any other problems mentioned by the commenters about whether you even have a value in the filterID variable. I heartly concur with the recommendation to use parameterized queries.
Edit: The single quotes go inside the double quotes.
SQlQuery = "SELECT * FROM v_InternImport
WHERE iID IN (SELECT iID FROM v_InternImport
WHERE " & filterColmn & " = '" & filterID & "')"