Ocean Knight Ocean Knight - 11 months ago 54
SQL Question

How to include an integer value in a SQL (Delete) statement in delphi

In the database the DoctorID is a integer column. Neither of the edited out "//" lines of code work. I would really appreciate it if someone could show me how to correctly specify integer values in a SQL statement.

procedure TForm1.btnDeleteDocClick(Sender: TObject);
iID : Integer;
iID := StrToInt (InputBox('Delete Doctor','Please enter in your Doctor ID',''));
with dmHospital do
//qryDoctors.SQL.Add('DELETE FROM Doctors WHERE DoctorID = iID ' ) ;
//qryDoctors.SQL.Add('DELETE FROM Doctors WHERE DoctorID = ' + QuotedStr(iID));
qryDoctors.SQL.Add('SELECT * FROM Doctors');

Answer Source

The problem with

qryDoctors.SQL.Add('DELETE FROM Doctors WHERE DoctorID = iID ' )

is that it doesn't introduce the value of the variable iID into the DELETE statement, as you've obviously gathered.

Equally, the problem with

qryDoctors.SQL.Add('DELETE FROM Doctors WHERE DoctorID = ' + QuotedStr(iID))

is that it surrounds the value of iID with quotes, so that what the Sql engine which executes the DELETE statement actually sees is something like

DELETE FROM Doctors WHERE DoctorID = '99'

but DoctorID is an Integer column not a string one.

So, since your ID column is an integer column type, try this instead (but see below about the perils of Sql Injection):

qryDoctors.SQL.Add('DELETE FROM Doctors WHERE DoctorID = ' + iID);

Iow, you don't need quotes around integer values.

A parameterized version of your DELETE statement would be a better solution:

qryDoctors.SQL.Text := 'DELETE FROM Doctors WHERE DoctorID = :DoctorID';
qryDoctors.ParamByName('DoctorID').Value := StrToInt(iID);

One reason this is better is that it's immune to Sql Injection (see https://en.wikipedia.org/wiki/SQL_injection), whereas your way of doing it, by allowing the user to specify part of the SQL using the InputQuery and then concatenating it with the other DELETE text, is not. In fact, concatenating user input into a SQL statement is exactly the thing which allows the Sql Injection exploit - for instance a malicious user can tack another statement (or more) onto the end of the one you're building, e.g. DROP TABLE Employee (or worse). The opportunity for this user-subversion of the Sql statement never arises when the query is parameterised.

Fwiw, the reason I personally don't like using the Value property of a TParameter is that it's a variant, so subverts data-typing on the value specified.

Btw, iID isn't a very good name for a variable that's actually a string. The 'i' prefix usually leads readers to expect an integer.