How to get data out of a recordset in excel? - recordset

I have the following code:
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim AppPath As String
Set cn = CreateObject("ADODB.Connection")
AppPath = Application.ActiveWorkbook.Path
Set rs = CreateObject("ADODB.RecordSet")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & AppPath & "\Masterlist_Current_copy.accdb;"
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"
cn.Open strConnection
Set rs = cn.Execute(strSql)
'Need Code here to get Info out of recordset
I am trying to get information out of the recordset that has the query result being dumped into it. I'm trying to figure out how to query the recordset and get the number of rows with a specific value in the "Neptune Number" field. I will then insert the correct number of rows into the worksheet I'm modifying. After that I need to get the data for that value and insert it into the worksheet.
Note: I don't care if recordset, datatable or anything else is used I simply need to be able to do what I described above. Please show code.

The easiest way to get where you I think you are asking to go is to modify your SQL statement changing
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"
to
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components] WHERE [Neptune Number] = 'Specific Value' ;"
This will force the sql query to only return the records you need. the .find method can be used for filtering the recordset, but i have avoided using it in this instance as it is cleaner to just ask the db for only the information that you want.
to process the recordset you can use the following
with rs
'will skip further processing if no records returned
if not (.bof and .eof) then
'assuming you do not need the headers
'loop through the recordset
do while not .eof
for i = 0 to .fields.count -1
'assuming the active sheet is where you want the data
cells(row, i + colOffset) = .fields(i).value
next
Rows(Row & ":" & Row).Insert
.movenext
loop
end if
end with
Where row is the starting point of your data and colOffset is the starting column of your data. Note that this code does not do things in the exact order you specified in your question (I am inserting rows as needed instead of calcualting the number of records up front.)
I have avoided using .recordcount because I find depending on the database used it will not return a correct record count.

Related

Passing parameters from Logic app to CosmosDB stored procedure with parameterized sql query

I am trying to call a stored procedure in CosmosDB from Logic App with some parameters to be able to retrive the number of documents that meet the query requirements.
Example of query I want to do:
SELECT * FROM c where c.Time_Stamp BETWEEN time1 AND time2
I have tried to test my stored procedure in Data Explorer. this what I was doing.
// SAMPLE STORED PROCEDURE
function sample(input) {
var context = getContext();
var collection = getContext().getCollection();
var response = context.getResponse();
//var inputtf = JSON.parse(input).id;
var filterQuery = "SELECT * FROM c where c.id = "+ input ;
console.log(filterQuery);
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
filterQuery,
function (err, feed, options) {
if (err) throw err;
response.setBody(JSON.stringify(feed));
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
As an input I was giving:
I get this an a result :
SELECT * FROM c where c.id = 220
So I can see that my query is able to get parameters in it.
The thing is I get no results for that query (Result is "[]")
This is my document I am trying to query:
This would be the kind of payload I would sent to the stored procedure to begin with. Next step would be to add a start time and end time parameters in UTC.
As an end goal, I would like to get in Logic App, in the output, a count of how many documents were meeting the query requirement.
If I'm not wrong, the partition key parameter for the execute store procedure activity should be sent as string. So, you need to add quotes between your partition key value.
In your case: "42976" instead of 42976
The stored procedures need a valid partition key value to be executed and to response the query. You can see a note in the top of this page from Microsoft documentation: https://learn.microsoft.com/en-us/azure/cosmos-db/sql/how-to-write-stored-procedures-triggers-udfs?tabs=javascript

Parsing Listbox results and updating values

The included code pulls parameters from a form and executes a stored procedure. The result is captured via a list box object and displayed on the form. How can I parse the result from the stored procedure, modify values, and then submit it back so the list box shows the updates?
My stored procedure returns a list of user accounts and their status (1,0). What I want to do is update the status from 1,0 to true,false so that when the results are shown in the form, the listbox shows true and false as opposed to 1,0.
Dim paramAcctNo As String
Dim paramProfileId As String
Dim query1 As String
Dim query2 As String
'Populating the form parameters
paramAcctNo = [Forms]![frm_userlookup]![lst_searchresults]
paramProfileId = [Forms]![frm_userlookup]![tb_hidden]
'Executing SP
query1 = "EXEC dbo.sp_ADCON_userDetailView '" & paramAcctNo & "','" & paramProfileId & "'"
'assigning results to listbox to display in form
Me.listbox1.RowSource = query1
If you are allowed to change the actual values in the query1 table after your stored procedure has run, you can run two simple UPDATE queries to change the 1s to True and the 0s to False.
UPDATE query1 SET [field name that contains the 1] = "True"
WHERE ([field name that contains the 1]="1")
UPDATE query1 SET [field name that contains the 0] = "False"
WHERE ([field name that contains the 0]="0")
A problem that you might run into is with a Type mismatch error. If the field containing the 0s and 1s is numeric, you won't be able to update it to a string value.

grails query for distinct entry

Hi I am trying to query my database by a specific property. Multiple entries in my database may have the same value for the property but I want it to return only the first entry that has that distinct value for the property.
For example, if my domain has a code property, then there might be an entry where "code" = "boy", and there might be another one where "code" = "girl" and there might be yet another one where again "code" = "boy". I want to query it so I get the first entry where "code" = "boy" and the entry where "code" = girl" but not the third entry where code is again equal to boy.
I was able to get the distinct code values from the database using both createCriteria() or namedQueries() but I am not able to get the whole object, just the value of code. How can I get the actual object?
Thinking about I came with an HQL query:
select d
from Domain d
where d.id = (select min(d1.id)
from Domain d1
where d1.code = d.code)

Sorting Datatable with linq with correct datatype of a column

hello I have this code that use to sort a datatable.
Dim sortingIndex As Integer = orderby
Dim DataTableNew As DataTable = New DataTable
DataTableNew = dt.Clone
Dim query = (From c In dt.AsEnumerable Order By c.Field(Of String)(sortingIndex) Ascending)
query.CopyToDataTable(DataTableNew, LoadOption.OverwriteChanges)
My problem is that with this method I always need (Of String) for it to work, so the date columns are also managed as Strings witch is the problem. Is there a way to use the correct type so the sorting is based on the type of the column?
Linq rocks, but sometimes the good old methods are better. You can do
dt.Select(string.Empty,dt.Columns[sortingIndex].ColumnName)
It sorts the DataTable using the column's data type.

how to compare string with sql date in grails

I have written query like this
Rule.findAll("FROM Rule WHERE client_id = ? " +
"AND DATE_FORMAT(contract_begins,'%d-%m-%Y') <= ?", [tripStartDate])
But it is not able to compare the sql date with string tripStartDate, how to solve this problem ,how to check contract_begins is less than or equal to tripStartDate.
The easiest way would be to construct a new data object from your string to pass into the query. Assuming (I may be misunderstanding) contract_begins is mapped as a date type in your Rule
Date tripStart = new SimpleDateFormat("dd-MM-yyyy").parse(tripStartDate)
Rule.findAllByClientAndContractBeginsLessThanEquals(client, tripStart)
or if you really want to keep the hql rather than dynamic finder
Date tripStart = new SimpleDateFormat("dd-MM-yyyy").parse(tripStartDate)
Rule.findAll("FROM Rule WHERE client_id = :clientId AND contract_begins <= :tripStart",
[clientId: client.id, tripStart: tripStart])

Resources