I have 2 tables related by ID on MS SQL. Delphi-interface looks like 2 DBGrids. By selecting one record from the top table, the bottom table shows all the records with this ID. DBGrid is connected to a stored procedure (TMSStoredProc) that simply displays all records with a given ID. Top table AfterScroll event:
Bottom_table_SP.ParamByName('#ID').AsInteger := Top_table_SP.FieldByName('ID').AsInteger;
Bottom_table_SP.Active := False;
Bottom_table_SP.Active := True;
Everything's very simple, and it works. But while I scroll fast top table, the whole form starts to blink - size of top-table and bottom-table changes in the millisecond. Does anyone know how to handle this kind of problem?
Since you mention SQL Server, I'm guessing you're using the ADO components (TADOStoredProcedure) here, so the normal MasterFields and MasterSource properties aren't available. You still have the basic functionality for other things, so you should use TDataSet.DisableControls and EnableControls to avoid this flickering:
Bottom_table_SP.DisableControls;
try
Bottom_table_SP.Active := False;
Bottom_table_SP.ParamByName('#ID').AsInteger := Top_table_SP.FieldByName('ID').AsInteger;
Bottom_table_SP.Active := True;
finally
Bottom_table_SP.EnableControls;
end;
You might find Disabling and Enabling Data Display useful to explain.
Related
i am trying to update a SQL-table with a button containing the function UpdateIf in PowerApps.
The button contains the following code:
UpdateIf(
'[dbo].[INVINFO]',
IVI_ID_NR = Dropdown_Inventur.Selected.Result && IVI_MANDANT = Dropdown_Mandant.Selected.Result,
{IVI_ERFSET_MENGE: IVI_LAGER_IST - IVI_VORTRAG_MENGE}
)
My Problem is that it only updates the first 100 rows.
Based on the Dropdown-selection, 500-3000 rows should be updated.
I can't find anything about this 100-rows limitation in the Microsoft-documentation, so my question is: Am i doing anything wrong? Is there an alternative to UpdateIf? (i tried ForAll & Patch, but it was very slow, so i dumped it)
Thanks :)
I found a workaround for this. I just made a stored procedure in the sql server that does this calculation. It works much faster and updates all rows, not just 100.
There are 2 tables linked by master-detail. When adding a new value to the detail table, the foreign key selected from the master table is not bound.
The M-D connection itself is performed on the form using two Dblookupcombobox and DataSource, ADOQuery for each, respectively.
enter image description here
Using the [ + ] buttons, new values are added that are not present in the combobox. But the problems start at the second [ + ] (aka detail), when creating a new line, you need it to bind the foreign key from the previous LookUpComboBox (Master). Button code of the second button [+]:
begin
Form4.ADOQuery1.SQL.Clear;
Form4.ADOQuery1.SQL.Add('Select City from City WHERE City='+#39+Form5.DBEdit1.Text+#39); //checking for duplicates
Form4.ADOQuery1.Open;
if Form4.ADOQuery1.IsEmpty then
begin
Form4.Query_city.FieldByName('City').AsString := Form5.DBEdit1.Text; //The PROBLEM is SOMEWHERE HERE! It Adds a new value without binding the foreign key
Form4.Query_city.Open;
Form4.Query_city.Post;
MessageBox(Handle, 'New data entered','Adding a new value',MB_ICONINFORMATION);
end
else
begin
Form4.Query_spec.Cancel;
Form4.ADOQuery1.Cancel;
MessageBox(Handle,PChar(''+Form5.DBEdit1.text+' already on the list!'),'Error',MB_ICONWARNING);
end;
end;
The new value is written to DBEdit1. It has a corresponding binding to tables.
So How i can insert field with with the corresponding foreign key?
You are making this unneccessarily difficult because of the way your
code is structured. Try something like this instead:
Open ADOQuery1, SELECTing its entire contents, with e.g.
procedure TForm4.OpenCitiesTable;
begin
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('Select City from City');
ADOQuery1.Open;
end;
and leave it open while the user does whatever operations lead to wanting to add a new city.
Then, when the users wants to add a city, call this procedure, e.g. supplying the City
value from Form5.DBEdit1.Text.
procedure TForm4.AddCity(ACity : String);
begin
ACity := Trim(ACity); // remove any leading or trailing blanks
// Do any formatting checks on ACity here, re.g convert it to Proper case
// check for adding a duplicate
if ADOQuery1.Locate('City', ACity, []) then begin
ShowMessageFmt('%s is already in the City table', [ACity]);
Exit;
end;
try
ADOQuery1.Insert;
ADOQuery1.FieldByName('City').AsString := ACity;
finally
ADOQuery1.Post;
// at this point you might want to refresh the contents of whatever source
// you are populating Form5.DBEdit1.Text from
end;
end;
I assume you can adjust the code relating to TForm4.Query_spec yourself;
Btw, you might want to consider using a TDBLookUpComboBox instead of your DBEdit1.
I'm only a beginner in learning to use Parameterised Queries as I used to do a lot of concatentating before. I've been trying to get this query below to work. It is a simple 'Book' table, with a field called 'BookTitle'. I have a simple textbox where I invite the user to enter any title...and it should run the query below to find if that book exists. Below is my code that, when run, manages to compile. However, when an entry into the textbox is added and the button to run the query is pressed, a Debugger Exception Notification appears with the following statement.
Debugger Exception Notification: Project Project1.exe raised exception class EOleException with message 'Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another'.
I then have the option to press 'Break' or 'Continue'. If I press 'Break', the line:
qbook.Parameters.ParamByName('BookTitle').DataType := ftString;
is filled with a purple/red colour (not sure what this means?).
That said, if I press 'Continue', the program will work as expected, and will continue to do so. Here is the code i've been testing.
procedure TForm4.btnRunQueryClick(Sender: TObject);
var BookEntry:string;
begin
BookEntry:=edtBookTitle.Text;
qbook.SQL.Text:='SELECT BookTitle FROM Book WHERE BookTitle = :BookTitle';
qbook.Parameters.ParamByName('BookTitle').DataType := ftString;
qbook.Parameters.ParamByName('BookTitle').Value := BookEntry;
qbook.Open;
end;
Further points to note: The components in my Delphi form are as follows
a TADOQuery named 'qbook',
a TDataSource,
a TDBGrid,
aTEdit into which the user enters their desired search criteria and
a TButton that once pressed, initiates the query.
With regards to the database, it is:
a MySQL database (Community Edition)
a table named 'Book', where BookID is the PK and is of INT data type.
a field entitled 'BookTitle' which i've set as VARCHAR(35). It is not part of the key. However, it is in the BookTitle field, that i want to apply my query.
NOTE: This answer was posted based on the original code in the question, which has been edited to match what is in my answer. See the question's revision history for the first version of the question on which my answer was based.
The solution you saw in the other post was correct; it was just for a standard TQuery and not TADOQuery. TADOQuery requires a couple of minor syntax changes:
Use Parameters.ParamByName() instead of Parameters
Set a DataType for each parameter before using it
Use .Value instead of .AsString
Here's a corrected version of your code (which also includes setting a value for BookTitle before using it.
procedure TForm4.btnRunQueryClick(Sender: TObject);
var
BookEntry:string;
begin
BookEntry := 'Some book title'; // or QueryEdit.Text or whatever
qbook.SQL.Text:='SELECT BookTitle FROM Book WHERE BookTitle = :BookTitle';
qbook.Parameters.ParamByName('BookTitle').DataType := ftString;
qbook.Parameters.ParamByName('BookTitle').Value := BookEntry;
qbook.Open;
end;
I have never known a string type query parameter need the datatype or whatever set, I would simply remove any reference to the datatype.
After all, if it hurts when you bang your head on a wall, just stop banging it.
I have done some searching and can't find a definitive answer to this one.
I am just getting into SQL so be gentle. Using D5, TNTUnicode, Zeos and SQLite3
I have a DBGrid with all the Account names in the tblAccounts showing.
I have a DBGrid with all the Folders in the tblFolders showing.
In the OnCellClick of the Accounts grid I have an SQL query
qryFolders.Close;
qryFolders.SQL.Clear; // Not really needed as I am assigning the Text next - but :)
qryFolders.SQL.Text:=
'SELECT Folder FROM tblFolders WHERE UPPER(Account)="FIRSTTRADER"'
qryFolders.ExecSQL;
tblFolders.Refresh;
In my application, nothing happens, I still have the full list of Folders visible.
In the SQL-Expert desktop that line works fine and displays only the two Folders associated with that Account. In that app it keeps displaying the full list of Folders
If I step through the OnCellClick it shows the correct Text etc.
Where am I going wrong?
Thanks
If you want to display a Master-Detail (Account as Master, Folder as Detail), so we start from here:
// connecting the grids
AccountsDataSource.DataSet := tblAccounts;
AccountsGrid.DataSource := AccountsDataSource;
FoldersDataSource := tblFolders;
FoldersGrid.DataSource := FoldersDataSource;
// retrieving the data
tblAccounts.Open;
tblFolders.Open;
That should reflect, what you already have. Now lets go to the Master-Detail.
It should be obvious that all Query and Table Components have a valid Connection set, so I will left this out.
First be sure, the Query is not active
qryFolders.Active := False;
Having a Master-Detail with a Query as Detail, we have to set the MasterSource
qryFolders.MasterSource := AccountsDataSource;
and after that we can setup the Query with parameters to link to the fields from MasterSource. Linking to the field Account in the MasterSource is done by using :Account
qryFolders.SQL.Text :=
'SELECT Folders FROM tblFolders WHERE UPPER( Account ) = :Account';
Now, we are ready to retrieve the data
qryFolders.Open;
Until this, we will not see any changes in the FoldersGrid, because we didn't told anyone to do so. Now let's get this to work with
FoldersDataSource.DataSet := qryFolders;
In your approach, you didn't Open the Query and you didn't link the Query to the Grid.
Another option is to have a Master-Detail without a separate Query.
(It seems there were some code refactoring, so i guess this is a working sample)
tblFolders.MasterSource := AccountsDataSource;
tblFolders.MasterFields := 'Account';
tblFolders.LinkedFields := 'Account';
Reference:
SourceForge ZTestMasterDetail.pas (see line 181ff)
SourceForge ZDataset.pas
I use jqGrid to display data which is retrieved using NHibernate. jqGrid does paging for me, I just tell NHibernate to get "count" rows starting from "n".
Also, I would like to highlight specific record. For example, in list of employees I'd like a specific employee (id) to be shown and pre-selected in table.
The problem is that this employee may be on non-current page. E.g. I display 20 rows from 0, but "highlighted" employee is #25 and is on second page.
It is possible to pass initial page to jqGrid, so, if I somehow use NHibernate to find what page the "highlighted" employee is on, it will just navigate to that page and then I'll use .setSelection(id) method of jqGrid.
So, the problem is narrowed down to this one: given specific search query like the one below, how do I tell NHibernate to calculate the page where the "highlighted" employee is?
A sample query (simplified):
var query = Session.CreateCriteria<T>();
foreach (var sr in request.SearchFields)
query = query.Add(Expression.Like(sr.Key, "%" + sr.Value + "%"));
query.SetFirstResult((request.Page - 1) * request.Rows)
query.SetMaxResults(request.Rows)
Here, I need to alter (calculate) request.Page so that it points to the page where request.SelectedId is.
Also, one interesting thing is, if sort order is not defined, will I get the same results when I run the search query twice? I'd say that SQL Server may optimize query because order is not defined... in which case I'll only get predictable result if I pull ALL query data once, and then will programmatically in C# slice the specified portion of query results - so that no second query occur. But it will be much slower, of course.
Or, is there another way?
Pretty sure you'd have to figure out the page with another query. This would surely require you to define the column to order by. You'll need to get the order by and restriction working together to count the rows before that particular id. Once you have the number of rows before your id, you can figure what page you need to select and perform the usual paging query.
OK, so currently I do this:
var iquery = GetPagedCriteria<T>(request, true)
.SetProjection(Projections.Property("Id"));
var ids = iquery.List<Guid>();
var index = ids.IndexOf(new Guid(request.SelectedId));
if (index >= 0)
request.Page = index / request.Rows + 1;
and in jqGrid setup options
url: "${Url.Href<MyController>(c => c.JsonIndex(null))}?_SelectedId=${Id}",
// remove _SelectedId from url once loaded because we only need to find its page once
gridComplete: function() {
$("#grid").setGridParam({url: "${Url.Href<MyController>(c => c.JsonIndex(null))}"});
},
loadComplete: function() {
$("#grid").setSelection("${Id}");
}
That is, in request I lookup for index of id and set page if found (jqGrid even understands to display the appropriate page number in the pager because I return the page number to in in json data). In grid setup, I setup url to include the lookup id first, but after grid is loaded I remove it from url so that prev/next buttons work. However I always try to highlight the selected id in the grid.
And of course I always use sorting or the method won't work.
One problem still exists is that I pull all ids from db which is a bit of performance hit. If someone can tell how to find index of the id in the filtered/sorted query I'd accept the answer (since that's the real problem); if no then I'll accept my own answer ;-)
UPDATE: hm, if I sort by id initially I'll be able to use the technique like "SELECT COUNT(*) ... WHERE id < selectedid". This will eliminate the "pull ids" problem... but I'd like to sort by name initially, anyway.
UPDATE: after implemented, I've found a neat side-effect of this technique... when sorting, the active/selected item is preserved ;-) This works if _SelectedId is reset only when page is changed, not when grid is loaded.
UPDATE: here's sources that include the above technique: http://sprokhorenko.blogspot.com/2010/01/jqgrid-mvc-new-version-sources.html