Parameter inside identifier - ms-access

I'm trying to write a add query that will change depending on the parameter. I have several queries:
LastK1StatDate
LastK2StatDate
.
.
LastK15StatDate
LastK16StatDate
My criteria should change depending on the value entered for the parameter "qryKioskNum" when the query is run.
Currently my criteria is this:
>Max("[LastK" & [qryKioskNum] & "StatDate]![K" & [qryKioskNum] & "LastDate]")
qryKioskNum is type Short Text
It keeps giving me the error "The expression is typed incorrectly, or is too complex to be evaluated."
Here is the complete SQL statement for this query:
PARAMETERS qryKioskNum Short;
INSERT INTO K1DispRejStat ( K1StatDate, K1BillCount1, K1BillCount2,
K1BillCount3, K1BillCount4, K1BillCount5, K1BillCount6, K1BillRej1,
K1BillRej2, K1BillRej3, K1BillRej4, K1BillRej5, K1BillRej6 )
SELECT DateValue([responseFrames]![dispDateTime]) AS [Date],
Sum(responseFrames.billCount1) AS SumOfbillCount1,
Sum(responseFrames.billCount2) AS SumOfbillCount2,
Sum(responseFrames.billCount3) AS SumOfbillCount3,
Sum(responseFrames.billCount4) AS SumOfbillCount4,
Sum(responseFrames.billCount5) AS SumOfbillCount5,
Sum(responseFrames.billCount6) AS SumOfbillCount6,
Sum(responseFrames.BillRej1) AS SumOfBillRej1, Sum(responseFrames.BillRej2)
AS SumOfBillRej2, Sum(responseFrames.BillRej3) AS SumOfBillRej3,
Sum(responseFrames.BillRej4) AS SumOfBillRej4, Sum(responseFrames.billRej5)
AS SumOfbillRej5, Sum(responseFrames.billRej6) AS SumOfbillRej6
FROM responseFrames, LastK1StatDate
WHERE (((responseFrames.kioskID)="K1"))
GROUP BY DateValue([responseFrames]![dispDateTime])
HAVING (((DateValue([responseFrames]![dispDateTime]))>Max("[LastK" &
[qryKioskNum] & "StatDate]![K1LastDate]")))
ORDER BY DateValue([responseFrames]![dispDateTime]);
currently everything is set to "K1" but I would like all reference to K1 to be dynamic
I think it is just a syntax issue but can't find how exactly this should be typed out.
Any help is great. Thanks!
*edited for clarity

In msaccess, create a PassThru query (because it retains the multi-line nice format).
Create // QueryDesign // Close // rightClick // SQLSpecific // PassThru
Paste in the following sql.
INSERT INTO kxxdisprejstat
(kxxstatdate,
kxxbillcount1,
kxxbillcount2,
kxxbillcount3,
kxxbillcount4,
kxxbillcount5,
kxxbillcount6,
kxxbillrej1,
kxxbillrej2,
kxxbillrej3,
kxxbillrej4,
kxxbillrej5,
kxxbillrej6)
SELECT Datevalue([responseframes] ! [dispdatetime]) AS [Date],
SUM(responseframes.billcount1) AS SumOfbillCount1,
SUM(responseframes.billcount2) AS SumOfbillCount2,
SUM(responseframes.billcount3) AS SumOfbillCount3,
SUM(responseframes.billcount4) AS SumOfbillCount4,
SUM(responseframes.billcount5) AS SumOfbillCount5,
SUM(responseframes.billcount6) AS SumOfbillCount6,
SUM(responseframes.billrej1) AS SumOfBillRej1,
SUM(responseframes.billrej2) AS SumOfBillRej2,
SUM(responseframes.billrej3) AS SumOfBillRej3,
SUM(responseframes.billrej4) AS SumOfBillRej4,
SUM(responseframes.billrej5) AS SumOfbillRej5,
SUM(responseframes.billrej6) AS SumOfbillRej6
FROM responseframes,
lastkxxstatdate
WHERE (( ( responseframes.kioskid ) = "kxx" ))
GROUP BY Datevalue([responseframes] ! [dispdatetime])
HAVING (( ( Datevalue([responseframes] ! [dispdatetime]) )
> Max([lastkxxstatdate]![kxxlastdate]) ))
ORDER BY Datevalue([responseframes] ! [dispdatetime]);
Name it kxxInsert (or some such, using kxx to say that it is generalized).
Then add this to the program
Sub getKxx()
Dim qrykiosknum As Integer ' temp here to have something
qrykiosknum = 3 ' temp here for an example
Dim kxxSQL As String, strSQL As String
kxxSQL = CurrentDb.QueryDefs("kxxInsert").SQL
strSQL = Replace(kxxSQL, "kxx", "k" & qrykiosknum)
'MsgBox (strSQL) ' it is too big to see all of it
Debug.Print strSQL
' then run strSQL
End Sub
Having dynamic tablename in MSAccess or MSSQLServer is possible when the Replace is done before executing the SQL.

I doubt you can make this work by using a query with a parameter. You are much better off using VBA. Use InputBox to get the variable portion of the query and DoCmd.RunSQL to run the query.

Related

conditional filter SSRS

My situation is
I have a parameter, this is a list, allowing multi values. That mean the first record in the list is 'Select All'
When user select All I need to include in my report all records that match with the list plus those that are blank. (My dataset is returning these)
When user select only 1 or a few I want to include only these records. No those that are blank
My problem:
I have a filter in my dataset that evaluate a parameter in a list, but I need to add a conditional filter to include a blank records when the selection will be "Select All"
I tried to use expression but this doesn't work
Filter expression
Fields!NAME.Value in = Parameters!List.Value !!!!!!!!!!!! Work Fine
But I need to change it like as
If Parameters!List.Value = 'Select All' Then
Fields!NAME.Value in = Parameters!List.Value or Fields!NAME.Value = " "
Else
Fields!NAME.Value in = Parameters!List.Value
End
Can you give an advice who can I resolve it please !!!
I'm working in SSRS R2
Thanks!!
This worked for me
Expression: =IIF(Parameters!pLocation.Value <> " All Locations", Fields!LOCATION.Value, FALSE)
Operator: =
Value: =IIF(Parameters!pLocation.Value <> " All Locations", Parameters!pLocation.Value, FALSE)
If you use Filter on your Dataset, try this:
Expression: [NAME]
Operator: IN
Value (fx): =Split(Replace(Join(Parameters!List.Value, ","), "Select All", " "), ",")
Try to work along this path. Basically you can reconstruct the multi value items into a string with Join(), and deconstruct it again into array by using Split(); where in between, you can manipulate them, for modifying (e.g. converting "Select All" into " "), adding (imitating "OR"), or removing extra items.
There is an alternative for this.
Add one more item to the paramater dataset values say "Not Available" as Label and value with the null. then there will be no change in the stored procedure and you can retrieve the data.
If the user select the specific item then he will get those values only. If he selects all then he will get the data for the null also with the all the others.
Hope this will help
You can put the logic in just one location if you do it this way.
You filter on the parameter, unless it's all values then the filter always matches.
Just a little cleaner.
Expression: =IIF(Parameters!pLocation.Value <> " All Locations", Fields!LOCATION.Value, " All Locations")
Operator: =
Value: =Parameters!pLocation.Value

MS ACCESS Retrieving "Table Description" Through Query

I've been looking everywhere for a way of accessing a table's description (same one that appears when you right click a table>table properties) through a SELECT query.
I tried using MSysObjects but I can only retrieve the name of the table using that.
Is it possible to do this through a query or is VBA needed?
As Remou says, you can't get it from a query (but you can include a function that returns it in a query). Here's another function:
Public Function GetTableDescr(stTableName As String) As String
On Error Resume Next
GetTableDescr = CurrentDb.TableDefs(stTableName).Properties("Description").Value
End Function
Here's a query that returns all the non-system tables, with their dates and descriptions (using the function above):
SELECT MSysObjects.Name, msysobjects.datecreate, msysobjects.dateupdate, GetTableDescr([Name]) AS Description
FROM MSysObjects
WHERE (((MSysObjects.Name) Not Like "~*") AND((MSysObjects.Name) Not Like "MSys*") and ((MSysObjects.Type)=1));
Finally, you can do an almost identical function for queries. The trick I found is that you only return non-inherited descriptions, otherwise if a query has no description you get the description of the queried object:
Public Function GetQueryDescr(stQryName As String) As String
On Error Resume Next
If CurrentDb.QueryDefs(stQryName).Properties("Description").Inherited = False Then
GetQueryDescr = CurrentDb.QueryDefs(stQryName).Properties("Description").Value
End If
End Function
The On Error Resume Next is necessary, because until the object has a description the property is null.
You can get the description from the table schema or from TableDef properties, but I do not think a standard query will work.
Set rs = CurrentProject.Connection.OpenSchema(adSchemaTables, _
Array(Empty, Empty, "Rules", Empty))
Debug.Print rs!Description
Using GetQueryDescr() above, you can run this query against the hidden sys table
SELECT MSysObjects.Name, GetQueryDescr([Name]) AS Properties, MSysObjects.DateCreate, MSysObjects.DateUpdate
FROM MSysObjects
WHERE (((MSysObjects.Name) Not Like "~sq_*") AND ((MSysObjects.Type)=5));
type 5 is for queries

how to change the date format as it not the same with the database

As the coding show at textbox 18/02/2012 (for example). but in database it is 02/18/2012.
TxtReqDate.Text = Calendar.SelectionStart.ToString("dd/MM/yyyy")
cboTermCode.Focus()
Calendar.Visible = False
But when i want to retrieve the related data for the date using coding below :
sqlCbo2 = "SELECT DISTINCT gear_code FROM gear WHERE est_start_date='" & TxtReqDate.Text & "'"
it say invalid date.
i cannot change the date format in the database.
if i change the code TxtReqDate.Text = Calendar.SelectionStart.ToString("dd/MM/yyyy") TO TxtReqDate.Text = Calendar.SelectionStart.ToShortDateString as it will appear 02/18/2012 at the textbox the data will appear but i want 18/02/2012 to appear at the textbox.
You could make use of STR_TO_DATE function to parse that data and transform it into a Date value.
Use it like this (correct any syntactical error):
where do i should put it. example??
sqlCbo2 = "SELECT DISTINCT gear_code FROM gear WHERE est_start_date=STR_TO_DATE('" & TxtReqDate.Text & "','%d/%m/%Y')"
This example is actually using the OleDbCommand but the syntax is similar for the SqlCommand: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
Dim comm As New OleDb.OleDbCommand(reportQueryString, conn)
comm.Parameters.Add("[ReportDate]", OleDbType.Date)
comm.Parameters("[ReportDate]").Value = dateVariable
You can see that when you add the parameter, you specify the dataType the command should convert your data type to. This way you're not doing raw string manipulation yourself.

How can you check for null in a VBA DAO record set?

I have an optional field in a database that I'm pulling out using a DAO Record Set. I need to check whether or not the field is set before I concatenate it with other fields. So far I have the following code snippet which I've tried with both Is and = (that's the obviously wrong syntax [[Is | =]]) to no avail. It appears that if I use = it will not correctly compare with Null and if I use Is then it complains that it's not comparing with an Object.
While Not rs.EOF
If rs.Fields("MiddleInitial") [[Is | =]] Null Then thisMiddleInitial = "" Else thisMiddleInitial = rs.Fields("MiddleInitial")
If prettyName(myLastName, myFirstName, myMiddleInitial) = prettyName(rs.Fields("LastName"), rs.Fields("FirstName"), thisMiddleInitial) Then
MsgBox "Yay!"
End If
rs.MoveNext
Wend
If there's a simpler way to do this I'm totally open to it. prettyName takes 3 Strings as parameters and initially I was just trying to pass rs.Fields("MiddleName") directly but it threw up at a Null value. I'd prefer to do something more direct like that but this is the best I could come up with.
How about:
IsNull(rs.Fields("MiddleInitial").Value)
You could also have a look at this article which has some explanation about Null values in Access VBA apps and how to handle them.
For the example you show, Nz would work:
thisMiddleInitial = Nz(rs!MiddleInitial,"")
Or simply concatenating the string with an empty string:
thisMiddleInitial = rs!MiddleInitial & ""
Your question has been answered by Remou, seems to me, but it occurs to me that you may just be trying to get proper concatenation of the name fields. In that case, you could use Mid() and Null propagation in VBA to get the result.
I don't use separate middle initial fields, so my usual name concatenation formula is:
Mid(("12" + LastName) & (", " + FirstName), 3)
The "12" string at the beginning is going to be tossed away if LastName is Not Null and ignored if it is null, because the + concatenation operator propagates Nulls.
To extend this to include middle intials would look like this:
Mid(("12" + LastName) & (", " + FirstName) & (" " + MiddleInitial), 3)
Assuming your UDF is not doing some kind of complicated cleanup of nicknames/abbreviations/etc., this could replace it entirely, seems to me.
If rst.Fields("MiddleInitial").Value = "Null" Then
This works for me. I use MS SQL Database.
I think the NoMatch option might work in this situation:
If rs.NoMatch = True Then
I prefer using the below to account for both Null and Empty string values. It's a good check to use you have forms collecting values from users.
If Trim(rs.Fields("MiddleInitial") & "") = "" then

Display Parameter(Multi-value) in Report

Can anyone tell me how to display all the selected value of my multi value parameter in SSRS report. When giving parameter.value option it gives error.
You can use the "Join" function to create a single string out of the array of labels, like this:
=Join(Parameters!Product.Label, ",")
=Join(Parameters!Product.Label, vbcrfl) for new line
I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:
Public Function ShowParmValues(ByVal parm as Parameter) as string
Dim s as String
For i as integer = 0 to parm.Count-1
s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
Next
Return s
End Function
Hopefully someone else finds this useful:
Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.
To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):
= "Select * from tProducts Where 1 = 1 "
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")
In your Parameter do the following:
SELECT -1 As ProductID, 'All' as ProductName Union All
Select
tProducts.ProductID,tProducts.ProductName
FROM
tProducts
By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.