Ms Access cannot get value from record set - ms-access

I'm working on an Access application (2007) in which there is an invocation of a stored procedure (SQL-Server 2012) which is supposed to return a simple result, a one column table with two records.
When executing the procedure within the Server Management Studio, it shows a result as follows:
+----------------------------------------------------------+
| One_Sticker |
+----------------------------------------------------------+
| This is the first record of the result |
| This is the second record of the result |
| This is the third and last record of the result |
+----------------------------------------------------------+
In my Access code I have (Note: I know this is to be done within a loop, but the following is for debugging purposes only):
Set RS = ADOCmd.Execute
Set blabla = RS.NextRecordset ' Get 1st record
<BP-1> Dummy_Variable = 1
Set blabla = RS.NextRecordset ' Get 2nd record
<BP-2> Dummy_Variable = 1
Set blabla = RS.NextRecordset ' Get 3rd record
<BP-3> Dummy_Variable = 1
Set blabla = RS.NextRecordset ' No more data.
<BP-4> Dummy_Variable = 1
[ means Breakpoint at this line]
I'm running this with a watch at blabla to see what is being assigned to it every step.
When looking at the watch on BPs 1, 2 and 3, blabla has a value while at BP 4 it is empty. This implies to me that the requred 3 records are indeed being returned.
The problem is the the Fields entry within blabla has nothing (and hence blabla.Fields("One_Sticker").Value is unknown).
How can i get the value of the One_Sticher field at blabla?
What am I doing wrong?
Thanks in advance for any useful suggestion.

In Access, I would normally:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT field FROM table WHERE somecriteria ORDER BY field;")
If rs.RecordCount > 0 Then
For x = 1 to 3
blabla = rs!One_Sticker
Debug.Print blabla
rs.MoveNext
Next
End If

Related

ACCESS sql code to multiply record with calculated value from previous cell

I am using Access Database to get a value. I am fairly new to access as I usually use SQLServer and I am having trouble in getting what I want.
I have the following table, with column TARGET and incremental Target as the target column that I need to get:
Category|Period|Value| TARGET |
A | 4 | 1 | 1/1 =1 |
A | 3 | 3 | 1/(3*1)=0.33 | (1/value at period 3 * previous target)
A | 2 | 6 |1/(0.33*6)=0.505|
A | 1 | 9 |1/(0.505*9)=0.22|
The data is partitioned by Category and ordered in descending order by Period.
For the first row the Target should be: (1/value at current period)
For the next rows the Target should be: (1/value at current period * value of previous target)
As you can see this is somehow complex as I need to evaluate a cell value and then for the next row I need to use the value in the cell above.
Plus I need to get the incremental value for this column as well.
Any help will be very much appreciated as I am new to Access and need to get this done soon!
Here is a function placed in general module that can be called from query. Value is a reserved word so I used Data for that field name.
Option Compare Database
Option Explicit
Global dblTar As Double
Global strCat As String
____________
Function CalcTarget(strC As String, dblT As Double) As Double
If strCat <> strC Then
strCat = strC
dblTar = dblT
End If
dblTar = 1 / (dblT * dblTar)
CalcTarget = dblTar
End Function
Calling function in query:
SELECT Category, Period, Data, CalcTarget([Category],[Data]) AS Target FROM Table1;
Normally I advise not to save calculated data to table when a query can work, but if you prefer to save, then options are:
An UPDATE action: UPDATE Table1 SET Target = CalcTarget([Category],[Data]);
Or VBA:
Sub CalcTarget()
Dim rs As DAO.Recordset
Dim strCat As String
Dim dblTar As Double
Set rs = CurrentDb.OpenRecordset("SELECT * FROM table1 ORDER BY Category, Period DESC")
strCat = rs!Category
dblTar = rs!Data
Do While Not rs.EOF
If rs!Category = strCat Then
dblTar = 1 / (rs!Data * dblTar)
rs.Edit
rs!Target = dblTar
rs.Update
rs.MoveNext
Else
strCat = rs!Category
dblTar = rs!Data
End If
Loop
End Sub

Access VBA write multiple values to single text field on form

I'm attempting to concatenate multiple values into a single text field on a form and needs help on assigning those values to the text field.
Setup: I have an access form that a user can select a drop down and choose an ID number. Selecting the ID and then clicking a button will run a query that can return one or multiple rows of results. The rows returned in the results will have duplicate data except for one field (e.g. description). I'm attempting to loop over the results and add the description to a text field on the form so that shows all the field values from each row, thus listing all the descriptions.
Example of data returned:
Columns:
ID | Issue Date | Description | CBD | ECD
Results return could be 1 or more rows: example below
17-0001 | 11/30/2017 | ABC | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | XYZ | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | LMN | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | QAZ | 12/5/2017 | 12/10/2017
In the text box I'm trying to add the values to I want it add the description to a single text box in order.
Text box contains:
Subject:
ID
Body Text:
ABC
XYZ
LMN
QAZ
Here is Code I have so far: It works but I just not sure how to get the description to concatenate together.
Private Sub createAnnouncement_Click()
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Dim db As Database
Dim issID As String
Set db = CurrentDb
Set qdf = db.QueryDefs("nso_announce_qry")
qdf.Parameters(0) = Forms![NSO Announcements]!annID
Set rst = qdf.OpenRecordset
annSubject = rst.Fields("Issuance Title")
Do While (Not rst.EOF)
MsgBox (rst.Fields("Issuance Detail Description").Value)
rst.MoveNext
Loop
End Sub
should there be a annBody variable outside the Do while that you add in each value as it loops through?
You can "acumulate" the contents of the Description field for each record:
Dim concatenated as String
Do While (Not rst.EOF)
concatenated = concatenated + rst.Fields("Issuance Detail Description") + " "
rst.MoveNext
Loop
concatenated = Left(concatenated, Len(concatenated) - 1)

Filtering Data from a specific column

Hello Everyone I am at a dilemma I am trying to find out a way to filter out certain data in a column field I have an idea on how to do this but I do not know the correct syntax to use. First here is the table and here is the code structure I would like to write.
for i=1 to length of column First Match
for j=1 to length of column Second Match
If ((value of the data in column First Match = 15) OR (value of the data in column FirstMatch = 1)) AND
((value of the data in column Second Match = 15) OR (value of the data in column Second Match = 1))
Then
Filter the data and append so the filtered datas are saved for both First Match and Second Match
end if
next
next
I am trying to filter out the data that is a 15 and 1 so that only data that have the values 0,2,3,4,5,6...14 will be shown for instance the information of john and steve will not be shown because both the first and second match fields have a 1 or 15 but the rest of data will be shown my form is a split form setup.
Is my method correct?
First Name Last Name First Match Second Match
James Matheson 0 2
Monroe Labonson 4 3
Barack Obama 2 5
Frederick Douglas 3 4
Steve MCGowan 1 1
John Seals 15 15
Mike Omalley 14 15
Set rs = CurrentDb.OpenRecordset("Table1")
Do While Not rs.EOF
If rs!Fields("First Match") > 1 And rs!Fields("First Match") < 15 And rs!Fields("Second Match") > 1 And rs!Fields("Second Match") < 15 Then
End If
Loop
With a better understanding (I hope) I've reproduced your data in Access and built a query that does what you seem to ask. The best way to see this is to create a new query, not add a table, and go directly to SQL view. Paste the following SQL statement (the one in quotes) in and replace matchFilter with your table name.
In your event code you can create a recordset based on the SQL:
Dim sSQL as string, rs as Recordset
sSQL = "SELECT matchFilter.[First Name], matchFilter.[Last Name], matchFilter.[First Match], matchFilter.[Second Match] " & _
"FROM matchFilter " & _
"WHERE ((([First Match]<>1 And [First Match]<>15 And [Second Match]<>1 And [Second Match]<>15)=True))"
Set rs = CurrentDB.OpenRecordset(sSQL)
' now do what you want
Wrong answer below!
Dim rs as Recordset
Set rs = CurrentDB.OpenRecordset("yourTableName")
Do While Not rs.EOF
If rs!Fields("col1") > 1 AND rs!Fields("col1") < 15 AND rs!Fields("col2") > 1 AND rs!Fields("col2") Then
'do what you have to do with filtered out records
End If
Loop
I have found the solution apparently it was just a misunderstanding because the first time I tried this code I thought it was wrong but it was because my field names did not have spaces in between the first time I wrote them.
Me.Filter = ""
Me.Filter = "[First Nam]<>'Jamie' AND [Last Nam]<>'Cartman'"
Me.FilterOn = True

How to get the current value of the nested for loop and the immediate for loop in Access 2010

I have an inventory table that is filled with the ID of the information in our inventory. There are other tables that have the name and ID of those categories.
I was hoping to use a for loop to fill the currect Inventory data with the IDs according to our inventory.
I was hoping to use a for loop to fill in the data to the InventoryNow table.
I was thinking of doing something like this.
For location.location_ID <= EOF
{
For years.years_ID <= EOF
{
insert into inventoryNow (wine_ID, years_ID, type_ID,language_ID, Amount)
values (2,currentvalue(years.years_ID), 1,1,currentvalue(locatio.location_ID,2))
}
}
Is there a function in Access 2010 for doing this?
Without seeing your data, I'm thinking this may be more suited to an append query if you are planning to do it for all records in the location and years tables. However it can be done in code by looping around with 2 recordsets similarly to what you've described, using something like the following code:
Dim dbs As DAO.Database
Dim rstLoc as DAO.Recordset
Dim rstYears as DAO.Recordset
Set dbs = CurrentDb
Set rstLoc = dbs.OpenRecordset("SELECT location_ID FROM location")
Set rstYears = dbs.OpenRecordset("SELECT years_ID FROM years")
If rstLoc.RecordCount > 0 And rstYears.RecordCount > 0 Then
rstLoc.MoveFirst
Do Until rstLoc.EOF
rstYears.MoveFirst
Do Until rstYears.EOF
DoCmd.RunSQL "INSERT INTO InventoryNow (wine_ID, years_ID, type_ID, language_ID, localtion_ID, Amount) VALUES (2, " & rstYears!years_ID & ", 1, 1, " & rstLoc.location_ID & ", 2)"
rstYears.MoveNext
Loop
rstLoc.MoveNext
Loop
End If
rstLoc.Close
Set rstLoc = Nothing
rstYears.Close
Set rstYears = Nothing
dbs.Close
Set dbs = Nothing
You can use SQL with MS Access and take advantage of a Cross join to create entries for each year and location:
SELECT wines.wine_ID, wines.type_ID,
wines.language_ID, wines.Amount,
years.years_ID, location.location_id
INTO AllWines
FROM wines, years, location
For example, with 2 wines ( and 2), 2 years (2010 and 2011) and 2 locations ( 1 and 2), you will get
wine_ID type_ID language_ID Amount years_ID location_id
1 1 1 10 2010 1
2 2 2 20 2010 1
1 1 1 10 2011 1
2 2 2 20 2011 1
1 1 1 10 2010 2
2 2 2 20 2010 2
1 1 1 10 2011 2
2 2 2 20 2011 2

Is there an easy way to populate an HTML table with SQL in ASP.NET 2.0?

I have 3 similar SQL queries that each will bring back 1 record with 5 fields.
I want to display each of these 3 records vertically in an HTML table.
Obviously I don't need sorting or paging so I don't want to waste overhead on a gridView.
<table>
<tr><td>Last</td><td>Col1</td><td>Col2</td><td>Col3</td></tr>
<tr><td>First</td><td>Col1</td><td>Col2</td><td>Col3</td></tr>
<tr><td>Middle</td><td>Col1</td><td>Col2</td><td>Col3</td></tr>
<tr><td>Gender</td><td>Col1</td><td>Col2</td><td>Col3</td></tr>
<tr><td>Birth Date</td><td>Col1</td><td>Col2</td><td>Col3</td></tr>
</table>
I want Col1, Col2 and Col3 to display results from their respective SQL queries.
What is the easiest way to go about this and could you provide an example?
Since they all have the same fields, UNION them together and set the result as the source for a grid control or repeater:
<asp:SqlDataSource ID="MyData" runat="server" ConnectionString="..."
SelectCommand=" (Query1) UNION (Query2) UNION (Query3) " />
<asp:GridView ID="ResultGrid" runat="server" DataSourceID="MyData" />
'
'begin sample data
Dim dt As New DataTable
dt.Columns.Add("Last")
dt.Columns.Add("First")
dt.Columns.Add("Middle")
dt.Columns.Add("Gender")
dt.Columns.Add("Birth Date")
'
Dim dr1 As DataRow = dt.NewRow
dr1("Last") = "apple"
dr1("First") = "is"
dr1("Middle") = "red"
dr1("Gender") = "male"
dr1("Birth Date") = "2009"
'
Dim dr2 As DataRow = dt.NewRow
dr2("Last") = "banana"
dr2("First") = "is"
dr2("Middle") = "yellow"
dr2("Gender") = "female"
dr2("Birth Date") = "2010"
'
Dim dr3 As DataRow = dt.NewRow
dr3("Last") = "cherry"
dr3("First") = "is"
dr3("Middle") = "pink"
dr3("Gender") = "both"
dr3("Birth Date") = "2011"
'end sample data
'
'
Dim sb As New StringBuilder
sb.Append("<table border='1'>")
sb.Append("<tr>")
sb.Append(String.Format("<td><b>Last</b></td><td>{0}</td><td>{1}</td><td>{2}</td>", dr1("Last"), dr2("Last"), dr3("Last")))
sb.Append("</tr>")
sb.Append("<tr>")
sb.Append(String.Format("<td><b>First</b></td><td>{0}</td><td>{1}</td><td>{2}</td>", dr1("First"), dr2("First"), dr3("First")))
sb.Append("</tr>")
sb.Append("<tr>")
sb.Append(String.Format("<td><b>Middle</b></td><td>{0}</td><td>{1}</td><td>{2}</td>", dr1("Middle"), dr2("Middle"), dr3("Middle")))
sb.Append("</tr>")
sb.Append("<tr>")
sb.Append(String.Format("<td><b>Gender</b></td><td>{0}</td><td>{1}</td><td>{2}</td>", dr1("Gender"), dr2("Gender"), dr3("Gender")))
sb.Append("</tr>")
sb.Append("<tr>")
sb.Append(String.Format("<td><b>Birth Date</b></td><td>{0}</td><td>{1}</td><td>{2}</td>", dr1("Birth Date"), dr2("Birth Date"), dr3("Birth Date")))
sb.Append("</tr>")
sb.Append("<table>")
'
Response.Write(sb.ToString)
In your service layer you should run the 3 queries and have your 3 unique result sets (hopefully you use datareaders instead of datatables and build actual objects) and then after you have data you then create a new List<MyObject> that matches the scope that you want on your table and build up that collection from your result sets. Then you can databind your clean List<MyObject> to your gridview, repeater, listview or similar control for generating the html output.
I recommend using the ListView control for all purposes as it allows you to generate the exact html you want and offers all the functionality you get with the gridview control of easily configurable alternating rows, databinding events etc.
My Two Cents: It's always hard to understand reasoning from the outside looking in especially since none of us want to reveal too specific of business usage on here, but it seems like your data design is what is actually flawed which is why it is hard to represent on screen.
It's not clear whether your data series are in rows or columns, but the Repeater is close to what you want, if your records are in rows.
Sorting and paging are not enabled by default on a Gridview, so there is no reason not to use one because of that.
However, you could consider using the ListView control, which gives you more control over templating.
If you are using SQL Server 2005+ you might try using the UNPIVOT option on your query first like this:
create table #mydata
(
id integer,
fld1 varchar(15),
fld2 varchar(15),
fld3 varchar(15),
fld4 varchar(15),
fld5 varchar(15)
)
go
insert into #mydata values (1,'fld 1 - rec 1','fld 2 - rec 1','fld 3 - rec 1','fld 4 - rec 1','fld 5 - rec 1')
insert into #mydata values (1,'fld 1 - rec 2','fld 2 - rec 2','fld 3 - rec 2','fld 4 - rec 2','fld 5 - rec 2')
insert into #mydata values (1,'fld 1 - rec 3','fld 2 - rec 3','fld 3 - rec 3','fld 4 - rec 3','fld 5 - rec 3')
go
--Unpivot the table.
SELECT idc, field, value
FROM
(SELECT cast(id as varchar(5)) idc, fld1, fld2, fld3, fld4, fld5 from #mydata ) d
UNPIVOT
(Value FOR field IN (fld1, fld2, fld3, fld4, fld5)
)AS unpvt;
returns results like:
idc value
----- ---------- ---------------
1 fld1 fld 1 - rec 1
1 fld2 fld 2 - rec 1
1 fld3 fld 3 - rec 1
1 fld4 fld 4 - rec 1
1 fld5 fld 5 - rec 1
1 fld1 fld 1 - rec 2
1 fld2 fld 2 - rec 2
1 fld3 fld 3 - rec 2
1 fld4 fld 4 - rec 2
1 fld5 fld 5 - rec 2
1 fld1 fld 1 - rec 3
1 fld2 fld 2 - rec 3
1 fld3 fld 3 - rec 3
1 fld4 fld 4 - rec 3
1 fld5 fld 5 - rec 3
Then you can use a gridView with auto-generated columns from that data source.