delphi create sql select statement at runtime - sql

I am attempting to create a sql statement in XE8 at runtime to search an oracle database based on the value in a textbox. I find multiple different ways that attempt to explain this online, but I am not understanding what it is asking.
I want to search a server based on a select statement and populate TDB components (labels only) based on the data. The furthest I have gotten is to get data populated, but the where
' ... somevalue = ' + textbox.text;
seems to have no effect.
What components do I need to make this happen? I am connected to the database, and it appears that I can get some kinda data out of it, but I can't seem to figure out how to filter the results. Obviously, I cannot create this sql statement at design time as the value of textbox.text will change depending on the user's input.

My error was in how to dynamically change what the data aware components got data as it would not always be the same. I had to manually go in and modify their datafield properties. Once I did this, my query functioned correctly.

Related

Choose AS400 query records directly from Excel

I've been searching the internet for hours trying to figure out if the following is even possible:
To choose the AS400 query records directly from Excel.
I haven't found any solution or description of how this could be achieved, which makes me guess that it's simply not possible. However, I haven't seen anyone confirm that it is impossible.
So my question is: Is this possible? And if it is, could you point me in the right direction in order for me to start learning how to do it?
I know its possible to run a query from Excel, and then adding parameters via SQL statements, but in my case, this presents several problems that could be avoided by choosing the records before the query is executed.
Example:
I have a query with a column (lets call it ColVal) that can hold the values 1 and/or 2. In the AS400 program under the menu "Work with queries" and then "Choose records" I can specify which records the query should contain when it has run based on the value in ColVal. This means i can get three different situations (A, B and C) when i run the query:
A) The query only contains records where the value in ColVal is 1
B) The query only contains records where the value in ColVal is 2
C) The query contains records where the value in ColVal is either 1 or 2
The goal is to be able to choose which situation I want from Excel in order to circumvent opening and using the AS400 program.
However, using situation C and then editing the query in Excel with an SQL statement to mimic situation A or B is not an option, as this means the query still contains undesired records.
This whole thing boils down to the following: Is it even possible to run the query from Excel essentially changing the data it contains and not just outputting it to excel? If this is possible, is it then possible to pass a parameter to the AS400 system and use it to create situation A, B or C?
I hope this example makes sense.
Edit - New example
Say i have different customers A and B. I can open the AS400 program and run a query in which i have specified that I only want data on customer A. I can then open Excel and use filters (as Hambone described) on the query to determine which records I want to output. However, if I want to work with data from customer B, I have to open the AS400 again and run the query with different parameters. I would like to be able to "change" my dataset from customer A to B from Excel, without having to include both in my recordset and then filter out one of them.
I imagined this is doable if you could pass a parameter to the AS400. The AS400 then runs the query using this parameter as the criteria for which records should be stored in the query. This means that if the parameter is Customer B, then there is no way to acces data from customer A, without running the query through AS400 again.
Any ideas are greatly appreciated :)
Follow up to my comment, here is a quick primer on how to run an ODBC query directly in MS Excel using Microsoft Query. This is very different than Power Query, which you referenced, in that MS Query is standard with Excel -- it's not a plug-in. This is relevant because it means everyone has it. If you are deploying a solution to others, that's an important consideration.
To start an MS Query in Excel, go to the data tab, select "From Other Sources" -> "Microsoft Query."
A list of your ODBC connections will come up. Pick the one that you want and select "OK."
It may or may not ask you for a login (depending on which ODBC connection you use and how its configured).
The next part is important. MS Query is going to try to have you use its builder to create the query. If you have the SQL, skip this part. It's horrible. Click "Cancel" on the query wizard, and then click the "SQL" button to enter your own SQL. If you can, make sure the result set is small (like use where 1 = 2 in the query).
When MS Query returns results, click the button next to the SQL Button to have it return the results to the spreadsheet. It looks like a little door.
From here, any time you want to refresh the query, you can simply right-click the data table in Excel and select "refresh." Alternatively you can go to the data tab on the ribbon and select "Refresh."
By the way if you have linked pivot tables and charts, the "Refresh All" option will refresh those as well, in the correct order.
To edit your query at any time, right-click on the table in Excel, go to Table-External Data Properties:
Then Click on the Connection Properties icon (highlighted below)
Click on the second tab (Definition) and edit the SQL Directly.
Parameters can be declared simply by inserting a bare "?" in place of your literal.
In other words, if your query looks like this:
select *
from users
where user_id = 'hambone'
Just change it to:
select *
from users
where user_id = ?
Excel will prompt you for a user id before it runs the query. From here, you also have the option of putting the parameter value in a cell within the spreadsheet and having the query read it from there. You'll see these when you right-click the table and go to the "Parameters" menu option.
Let me know if this helps or is unclear.
-- EDIT 7/23/2018 --
To follow up on your latest edit, it is possible to handle the scenario you describe, where you want to be able to filter on a value, or if none is given, then not have a filter. You see this a lot when you present multiple filter options to the user and you want a blank to mean "no filter," which is obviously counter to the way SQL works.
However, you can hack SQL to still make it work:
select * from activities
where
(activity = ? or ? is null) and
(energy = ? or ? is null)
In this example you have to declare four parameters instead of two, two for each.
You might also have to play with datatypes, depending on the RDBMS (for example for numerics you might have to say ? = 0 instead of ? is null or even ? = '' for text).
Here is a working example where a single filter was applied on the query above and you can clearly see the second one did not have an impact.
Yes it's possible. You need to use an ODBC driver to connect to the AS400 and retrieve the data. The driver and documentation are Here

How can I create a (server-side) filtered editable SQL recordset for Microsoft Access?

I am working on a very complex legacy ADP project in Microsoft Access that connects to a 2008 SQL Server back end. A common usage scenario is a form in datasheet view that contains an editable recordset.
The approach used through most of the database is to load the form, then build the SQL dynamically in VBA using form parameters, and apply the SQL as the RecordSource for the form. Many of the queries are quite complex, so this makes for really ugly code and a maintenance nightmare.
For the read-only recordsets, I have converted the dynamic sql to parameterized stored proceedures, which works great. Nice and clean, and easy to maintain going forward.
But for the editable recordsets, I am trying to determine the best approach:
1. Dynamic SQL - As mentioned above, I would really like to avoid this approach.
2. SQL View - The challenge here is that some of the tables are very large, so if I try to load the view and then filter it on the form, it has to pull the entire recordset from the SQL server, even though I only need a small number of rows. (Negative performance and IO impact.)
3. Use context_info - This sounds intriguing, but does not sound like a recommended approach based on discussion here: Create parameterized VIEW in SQL Server 2008 If I was developing against SQL Server 2016 I might look more into SESSION_CONTEXT.
4. Parameter Table with View - This is an idea that I am leaning towards. I would create a Parameters table in SQL, and set the parameter value (as a key/value pair) with the session ID. The view would then filter based on the current value in the parameter table. This would allow me to use a view as my RecordSource to support the edits, but the filtering would take place on the SQL Server side.
Is the parameter table indeed the best approach to take with this project, or is there another way that I could access a parameterized read-write recordset that is filtered on the server side?
I assume you talking about a non adp project now.
Even if you don’t use a view, and say bind a form directly to a linked table of 1 million rows, then access will ONLY pull down the records you requests. You simply just use the forms “where” clause of the open Form command.
So you don’t even have to use dynamic sql here.
However, you don’t want to launch a form bound to large table UNLESS you set the where clause.
You can certainly open a form without a reordsource, have the user enter some parameter values into a text box, and then go:
Dim strSQL as string
strSQL = "select * from tblCustomers where InvoiceNum = " & me.MyInvoiceTextBox
Me.RecordSoruce = strSQL
However, in most cases you better to create some type of search form. Let the user enter some values, display the results like this:
So in above, the person type in "smi". You display the results
(and in above I did use the above approach of stuffing the sql directly into the forms reocrdsource
Now on the edit buttons along the side to launch + edit one record,
I simply go:
Docmd.OpenForm "frmCustomer",,,id = & me!id
Once again, EVEN if the form is bound directly to the linked SQL server table, only the ONE record will be pulled from SQL server. So no messing with sql, no messing with parameters etc. is required.
So a regular non ADP access application with linked tables DOES NOT pull the whole table.
You can also after opening a form set the forms filter – and again access will ONLY pull the reocrds in question from the linked sql table. It is a “common” myth that access pulls all records – it does not if you provide a filter, and I recommend you open a form to one record, let the user work then close the form and return back to some search screen in which you ready to do battle with the next customer etc.
so provide a search form - don't recommend having the form to edit data be all cluttered up with the ability to search records. Let the user edit, and then close the form - this also promotes the record being saved after the user done working.
edit:
For a form that has any kind of complex joins etc., then create a view, and bind the form to that view. You use the forms "where" clause, then once again access will only pull down the one record. So for complex joins etc., yes access can often mess that query up and it runs slow. So if the form is bound to one table (that is MOST cases), then bind the form directly to the linked table. If the sql is complex, then bind the form to the linked view, and as noted in either case ALWAYS provide a "where clause" to the openform command - it will in these cases ONLY pull the one record into the form. And once again, no messy parameters, no messy sql is required on the access side - you will save MASSIVE amounts of coding if you adopt this approach, and you also get stellar performance since you limiting the reocrds pulled into that form from sql server.

SSRS - Fields working in Data Set, but won't appear in report

I have a data set that gets its values from a stored procedure, and I'm positive that the stored proc is working correctly since I'm getting results in SQL Server. However, when I call the fields in an expression (for example, =Fields!CustomerName.Value) and preview, it just displays a blank spot in its place. If I simply typed some text in that spot, the text does appear when I run it.
The DataSet IS working, and it's refreshed to show all of the fields. They just don't display anything in the report, despite definitely returning values when I check in SQL Server. Does anybody have any suggestions as to what steps I could take to fix this?
Thanks.
Try referencing your dataset explicitly, by changing this:
=Fields!CustomerName.Value
To this:
=Fields!CustomerName.Value,"MyDatasetName"

How to get info from a listbox populated by an SQL query?

The title says the vague question, but, I will be more specific. I'm more of a hardware oriented person with some experience in VB, Java, and C++. I've been asked to modify a form in Access which uses SQL queries to take information from a database. The edit I am trying to make is to a form that has selections to narrow down the data it queries from to appear in a listbox in the center of the form (so, like radio buttons to specify a certain height or weight of an object in the database). The selections, as they are selected, concatenate additional specifications to an string that is then run as an SQL query. What I am trying to accomplish is to take a column of the narrowed-down data and find the maximum number in the column and the average of the numbers in the column. It seems really simple and know how to do that with regular lists and arrays, but I'm at a loss with my limited knowledge. I've considered making another SQL string, but in another part of the form, it was done with two strings (so, one to put the data in the listbox from the database and one to pull the specific column of the narrowed down data). That being said, it doesn't seem logical to me to pull the same sets of data each time, so I'm wondering if I can just pull the info from the already pulled info. At the bottom of the code set is this:
ItemList.RowSource = vSQLStock
ItemList = Null
ItemList.Requery
QuoteList.RowSource = vSQLNonStock
QuoteList = Null
QuoteList.Requery
Both vSQLStock and vSQLNonStock have their own sets of SQL strings that are run by this function, or as far as I can tell (I'm still studying up on SQL) put the narrowed down items in the QuoteList listbox. What I'm asking is if there is a way with any function that can be used to go through this information? Specifically, take a column and do some calculations on the data. I don't want to run another SQL query and bog down the server, but rather manipulate the data on the user's computer.
An example of what happens is the user selects whether the item is stock/nonstock, searches by the name/code/ID, and then puts all the matches on the listbox on the form. The listbox shows lines of data with columns like Name, Cost, Size, Weight, etc. of which I am looking to do calculations on the Cost column. Hopefully this is enough information; I appreciate any advice.
It looks from your question like you are attempting to get the Maximum and the Average from a SQL query.
the syntax:
SELECT MAX(myColumn) as MyMax, AVG(myColumn) as MyAverage
FROM myTable
WHERE . . .
Will return the Maximum and Average Values within SQL Server or within MS Access
If you're really bound and determined to do this locally with the data you've already retrieved from the server, then you probably need to look into working with adodb.recordsets. You can kind of treat it like an array. Kind of.
I really recommend querying the server for the data you need though. It's a world simpler.
dim rs as ADODB.Recordset
Set rs = QuoteList.Recordset
rs.MoveFirst
Do Until rs.EOF
' loop through recordset doing something
rs.MoveNext
Loop

MS Acess 2003 - VBA for Update SQL query?

hey guys, could someone show me the simple update query through vb? I need to add new fields to the table (just 3) and add a couple text boxes on a form so that users can add some additional data relative to the record (which is already what this form is based on).
So the first form I have is a form that populates a list, when the user double clicks on a selection from that list, it opens a new form, so that the ID of the the table that is tied to this form that I need to add the these text boxes on (all the combo boxes and text boxes relative to one record are tied to the active form at this point, however there are all unbound. On a button click there is already vb that saves the information to the table). I did not create this however, it was built by someone who is not there anymore, and apparently is better than I at this stuff. My problem is that there is soooo much vb that checks for records, and various sql statements based on case, that I cannot decipher it to its simplest form.
So I was looking for a simple example of an update sql statement in vb so I can try to break this apart.
I need it to update the record based on the ID: sql WHERE RecordID = me.RecordID
I actually thought I knew how to do this based on examples, however every time I try, then try to run on button click, I get a run-time error of SYNTAX error, and the debug just highlights the db.execute(sql) part. So I tried to get the resulting immediate window of the sql statement, and it looks fine to me:
UPDATE tblMain
SET [Name] = "John Doe",
[DATE] = #9/30/2009#,
[TYPE] = "TypeA",
WHERE RecordID = 958;
Can I update a table without accounting for every field in the table (because this one has about 15 plus the new 3, so I am ignoring about 14 fields here, but I do not want to alter those anyway???
So as always, I appreciate the help yall!! Thanks!
EDIT:
Sorry I always forget this....I was actaully trying it DAO....
Dim db as DAO.Database
Dim sql as String
set db = CurrentDb
etc
You were thaaat close! You have a simple extra comma after your last column. Get rid of it and it works fine.
UPDATE tblMain SET
[Name] = "John Doe",
[DATE] = #9/30/2009#,
[TYPE] = "TypeA"
WHERE RecordID = 958;
Yes, you can absolutely update only a few columns rather than all of them. That is a best practice, BTW.
Finally, It's considered bad practice to name your columns after reserved words like "Name" and "Date", but I know you inherited this.
You were wise to include Debug.Print sql in your code. bpayne already pointed out the extra comma in your SQL statement.
I want to point out another trouble shooting technique you may find useful to debug SQL statement problems.
Copy the statement from the Immediate Window, and paste it into the SQL View of a new query. Modify the query in the query designer until you can get it working, then revise your VBA code to generate a matching SQL statement.
In this case you might not have noticed the extra comma. However, you could create another new query and build the UPDATE statement from scratch in the query designer. After getting that one working, you could compare its SQL View to the failing query.