Delphi/Lazarus Filter MSAccess data by SQL Query using DateTimePicker - sql

I would like to filter data from MS Access and get them to the LazReport.
I tried few combinations of code but none of them worked. I am still getting error "Types of data does not equal in critteria expression".
MS Access field is set to Date/Time with format Short Date (01.01.2017).
DateTimePicker is set to YMD (Year, Month, Day).
This is my code:
procedure TForm12.BitBtn1Click(Sender: TObject);
begin
If ListBox1.ItemIndex=0 then
ReportSelected.Caption:=Listbox1.Items[Listbox1.ItemIndex];
If ListBox1.ItemIndex=1 then
ReportSelected.Caption:=Listbox1.Items[Listbox1.ItemIndex];
If ListBox1.ItemIndex=2 then
ReportSelected.Caption:=Listbox1.Items[Listbox1.ItemIndex];
If ListBox1.ItemIndex=3 then
ReportSelected.Caption:=Listbox1.Items[Listbox1.ItemIndex];
If (ReportSelected.Caption='Production Overview') And (DBLookUpListBox1.ItemIndex <> -1) And (CboShift.ItemIndex = 0) then
begin
SQLQuery_ReportShift.Active:=true;
SQLQuery_ReportShift.Close();
SQLQuery_ReportShift.SQL.Text:='SELECT ProductionDate, Shift, AssemblyLine, Product, OperatorsAvailable, ProductionTime, CleanProductionTime, DowntimeTime, GoodParts, ScrapTotal, ScrapRate, QualityRate, Availability, Performance, OEE FROM ProductionInfo WHERE AssemblyLine='''+DBLookUpListBox1.Items[DBLookUpListBox1.Itemindex]+''' AND ProductionDate='''+FormatDateTime('dd/mm/yyyy', DateTimePicker1.Date)+'''';
SQLQuery_ReportShift.Open();
frReport1.LoadFromFile('ProductionOverview.lrf');
frReport1.ShowReport;
end;

If I remember correctly Access uses the date in the order Y/M/D and puts '#' characters around it:
function AccessDate(d:TDateTime) : string;
var
yy,mm,dd : word;
begin
DecodeDate(d, yy,mm,dd);
result := Format('#%d/%d/%d#', [yy,mm,dd]);
end;
As for DateTimePicker to return only date: Turn off time parts by checking dtpHour, dtpMinute and dtpSecond in HideDateTimeParts.

Related

SAP HANA SQL Query with Dynamic Placeholder

I have a query that is passing the current year as a placeholder parameter that right now is hard coded. How can I have this just pass the current year? I've seen a few different potential solutions but most of them are in HANA Studio or involve dynamic SQL generation.
I'm putting the SQL into Tableau so those are both off the table.
...sum("StockInQualityInspection") as in_quality,
sum("StockInTransit") as its
from "_SYS_BIC"."stream.models.marketing.poly/InventoryQuery" ('PLACEHOLDER' = ('$$IPCurrentYear$$', '2018'))
where "StockValuatedUnrestrictedUse" <> 0 or "StockInQualityInspection" <> 0 or "StockInTransit" <> 0
group by case when "ReceivingPlant" is null then "Plant" else "ReceivingPlant" end,
case....
Remove the parameters input of your CV
Add this expression: year(now())
If you don't have access to manipulate the CV, into your query use:
('PLACEHOLDER' = ('$$IPCurrentYear$$', select year(now()) from DUMMY))
Regards
while placing a query is not permitted, you can pass a parameter as following
do begin
declare lv_param nvarchar(100);
select max('some_date')
into lv_param
from dummy /*your_table*/;
select *
from "_SYS_BIC"."path.to.your.view/CV_TEST" (
PLACEHOLDER."$$P_DUMMY$$" => :lv_param
);
end;
more can be found here
credit to #astentx

How can I calculate all field and post (SQL/or onCalcFields)

I want to calculate all fields and add a total field. How can I do this? I did this with sql command, but I don't know how to update dbgrid every time.
My code:
procedure TForm1.Button1Click(Sender: TObject);
begin
ADOQuery1.Close;
ADOQuery1.SQL.Text := 'select names,big1,small1,black1,big2,small2,big3,'+
'((big1+small1+black1+big2+small2+big3)*0.35) as total from adlar7v';
ADOQuery1.Open;
end;
when I run this code the first time it works, but the second time the changes don't appear in the grid.
Second method:
I did this with the TAdoQuery.OnCalcField event but there is a problem.
I know how to calculate a field but I don't know how to multiply all field after addition
my code:
ADOQuery1.FieldValues['total'] :=
ADOQuery1.FieldValues['big1'] + ADOQuery1.FieldValues['small1'] +
ADOQuery1.FieldValues['black1'] + ADOQuery1.FieldValues['big2'] +
ADOQuery1.FieldValues['small2'] + ADOQuery1.FieldValues['big3'];
ADOQuery1.FieldValues['cemi']:=((ADOQuery1.FieldValues['boyuk1'] + ADOQuery1.FieldValues['boyuk2'] + ADOQuery1.FieldValues['boyuk3'])*0.35)+((ADOQuery1.FieldValues['kicik1'] + ADOQuery1.FieldValues['kicik2'])*0.25)+(ADOQuery1.FieldValues['qara1']*0.30);
Hi I want to post calc field(cemi) to table (sql). when I calc all field the last field doesn't post on sql table. because last field (cemi) type fkcalc how can I post fkcalc type field Thanks in advance!
when I run this code first time working second time changes doesn't appear db grid
Use the Object Inspector to set up an AfterPost handler on your AdoQuery1:
procedure TForm1.ADOQuery1AfterPost(DataSet: TDataSet);
begin
AdoQuery1.Refresh;
end;
Then, after you save a change to one of the numeric columns in the grid, the AdoQuery1.Refresh will cause the data to be retrieved again from the server, and that will cause the server to recalculate the "Total" column. The fact that it isn't doing that at the moment is why the Total column isn't updating.
Btw, if I've understood what you are asking about that correctly, then your second point
I know how to calculate field but don't know how to multiplication(*) all field after (+)
Use the following code for this
ADOQuery1.FieldValues['total'] := (
ADOQuery1.FieldValues['big1'] + ADOQuery1.FieldValues['small1'] +
ADOQuery1.FieldValues['black1'] + ADOQuery1.FieldValues['big2'] +
ADOQuery1.FieldValues['small2'] + ADOQuery1.FieldValues['big3'] )
* 0.35;

How to display records with certain date from an editbox using ms access and delphi 7

I have a table in MS Access with a name MembersAccount and one of the field name as DatePaid. I am trying to display records from a date entered in an editbox but the output is not displaying any records at all. This is the code I am using.
if ADOQuery1.Locate('datepaid',edit1.Text,[]) THEN
begin
open;
SQL.Clear;
qry:= 'Select * from MembersAccount WHERE((MembersAccount.[DatePaid])='+edit1.Text+')';
SQL.Add(qry);
Active:= True;
Where am I getting the code wrong? Date entered in the editbox is in dd/mm/yyyy format
Use parts like these (not full code):
editStr := edit.Text;
myDate := StrToDate(editStr);
sqlDate := FormatDateTime('yyyy/mm/dd', myDate);
qry:= 'Select * from MembersAccount WHERE((MembersAccount.[DatePaid]) = #' + sqlDate + '#)';

Oracle UPDATE has no effect

I am working on Sql Developper an I created the following procedure in a package:
PROCEDURE VALIDER(a_session IN NUMBER) AS
i NUMBER;
TYPE type_tab IS TABLE OF PANIER%ROWTYPE;
tabSeances type_tab;
BEGIN
SELECT * BULK COLLECT INTO tabSeances
FROM PANIER
WHERE a_session = sessionweb;
i:=0;
FOR i IN 1 .. tabSeances.count LOOP
-- UPADTE DU NOMBRE DE PLACES LIBRES
BEGIN
UPDATE PROJECTION
SET remaining_seats = (remaining_seats - tabseances(i).nbrplaces)
WHERE num_copy = tabseances(i).num_copy
AND day = tabseances(i).dateseance
AND time_slot = tabseances(i).time_slot
AND movie = tabseances(i).movie;
COMMIT;
--UPDATE ON PANIER
UPDATE PANIER
SET valide = 1
WHERE sessionweb = a_session
AND num_copy = tabseances(i).num_copy
AND dateseance = tabseances(i).dateseance
AND time_slot = tabseances(i).time_slot
AND movie = tabseances(i).movie;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN raise_application_error(-20035, 'Pas de données');
WHEN OTHERS THEN raise_application_error(-20006,'Autres Erreurs');
END;
END LOOP;
END VALIDER;
The procedure executes normaly and I don't get an error.
I have a kind of product cart: "PANIER". I loop all the entries in thsi cart for one person (session) to validate them in the database and decrement the total number of seats.
But the field "remaining-seats" (from PROJECTIONS) in the first update don't work. The field isn't updated. I have already tried with other values but nothing.
I am sure that the procedure is executetd because the second update still works. It marks the cart entry as "CONFIRMED".
I don't have any trigger on this field.
My tables contains valid data (<>NULL).
I execute this procedure like this (in a BEGIN END; block):
CMDPLACES.VALIDER(1);
Thank for your reply.
Is it day or dateseance in your first update?
UPDATE PROJECTION
SET remaining_seats = (remaining_seats - tabseances(i).nbrplaces)
WHERE num_copy = tabseances(i).num_copy
AND dateseance = tabseances(i).dateseance
AND time_slot = tabseances(i).time_slot
AND movie = tabseances(i).movie;
Also as #ThorstenKettner was mentioning, the timestamp data in the date , may fail while comparing, so we have TRUNCATE the timestamp data using TRUNC() [if needed]!
If the date column is indexed, beware the index will not be used by the database .
To handle NO Data in UPDATE, you can check (SQL%ROWCOUNT > 0) to identify the number of rows updated!
Your first update compares days. What data type are these? In case you deal with DATETIME, make sure to compare without the time part if any. Use TRUNC to achieve this.
AND TRUNC(day) = TRUNC(tabseances(i).dateseance)

Type mismatch in expression in Delphi 7 on SQL append

I have a code, that checks the current date when a form is loaded, performs a simple calculation, and appends a SQL in Delphi. It works on Windows 7 with Delphi 7, and on another computer with Xp, but doesn't on 3 other computers with Xp. When the form is loaded it shows a "Type mismatch in expression", and points to the line after the append. What could be the problem?
procedure TfmJaunumi.FormCreate(Sender: TObject);
var d1, d2: TDate;
begin
d1:= Date;
d2:= Date-30;
With qrJaunumi do
begin
Open;
SQL.Append('WHERE Sanem_datums BETWEEN' + #39 + DateToStr(d1) +
#39 + 'AND' + #39 + DateToStr(d2) + #39);
Active := True;
end;
end;
As robsoft says, it is probably the internationalisation settings. You could use parameterised queries instead - they are generally simpler if using dates and times.
Also, the Open after the with's begin isn't needed - in fact it will open the query without the WHERE clause you are adding.
procedure TfmJaunumi.FormCreate(Sender: TObject);
var d1, d2: TDate;
begin d1:= Date; d2:= Date-30; With
qrJaunumi do
begin
SQL.Append('WHERE Sanem_datums BETWEEN :StartDate AND :EndDate');
// exact expression will vary according to DB connection type.
// Example is for TADOQuery.
Parameters.ParamByName('StartDate').Value := d1;
Parameters.ParamByName('EndDate').Value := d2;
Active := True;
end;
end;
You may use a prepared statement to overcome any localization problems with date time values. DateToStr depends on the client side. FormatDateTime can fail if the server's localization doesn't accept the date format.
procedure TfmJaunumi.FormCreate(Sender: TObject);
var
d1, d2: TDate;
begin
d1:= Date;
d2:= Date - 30;
//qrJaunumi.SQL.Clear; removed because it would remove the "SELECT ... FROM ..." part
qrJaunumi.SQL.Add('WHERE Sanem_datums BETWEEN :StartDate AND :StopDate ');
qrJaunumi.Prepared := True;
qrJaunumi.ParamByName('StartDate').AsDateTime := d1;
qrJaunumi.ParamByName('StopDate').AsDateTime := d2;
qrJaunumi.Open; // = qrJaunumi.Active := True;
end;
The space after ":StopDate" is important because Delphi has a bug in the parameter parser unless they fixed it in newer versions.
It's almost certainly to do with the local internationalisation settings on those computers - DateToStr will return a string in the local date format (possibly MM/DD/YYYY or DD/MM/YYYY) - and depending on where you are this might not be what you're expecting.
I suspect you'll find that the computers it's not working on think they're in a different country/use a different internationalisation setting to the computers where it's working.
A better solution would be to use FormatDateTime to get the date into a standard format that your SQL Server installation will accept, so there's no chance that any local 'internationalisation' settings can interfere like this.
Unfortunately none of the above worked, but the solution was to replace the Format with "yy.mm.dd." instead of "yyyy.mm.dd.", and adding single quotes. Weird, it says the format is "yyyy.mm.dd." everywhere.
The code looks like this now:
procedure TfmJaunumi.FormCreate(Sender: TObject);
var d1, d2: TDate; d3, d4, atd: String;
begin
d1:= Date;
d3:= FormatDateTime('yy.mm.dd.',d1);
d2:= Date-30;
d4:= FormatDateTime('yy.mm.dd.',d2);
atd := '''';
With qrJaunumi do
begin
Open;
SQL.Append('WHERE Sanem_datums BETWEEN'+ atd+d4+atd +'AND'+ atd+d3+atd+';');
Active := True;
end;
end;
Hi I had same error and found different solution from MS Support:
SQL.Text:='Delete * from TableName where((kno='+(inttostr(userNo))+')and(Sanem_datums >= # '+(FormatDateTime('mm-dd-yy',d1))+' # ))'; ExecSQL;
https://support.microsoft.com/en-us/kb/175258