delphi使用SQL的教程7

{ Initialize the variables needed to run the query }

 

with ListBox1 do

if ItemIndex = -1 then

raise Exception.Create(’Can’’t Run Query: No Alias Selected’)

else

strAlias := Items.Strings[ItemIndex];

 

with ListBox2 do

if ItemIndex = -1 then

raise Exception.Create(’Can’’t Run Query: No Table Selected’)

else

strTable := Items.Strings[ItemIndex];

 

with ListBox3 do

if ItemIndex = -1 then

begin

if ComboBox1.ItemIndex > Ord(soNocondition) then

raise Exception.Create(’Can’’t Run Query: No Field Selected’)

else

strField := ’’;

end

else

strField := Items.Strings[ItemIndex];

 

if (Edit1.Text = ’’) and

(ComboBox1.ItemIndex > Ord(soNoCondition)) and

(ComboBox1.ItemIndex < Ord(soBlank)) then

raise Exception.create(’Can’’t Run Query: No Search Value Entered’)

else

strValue := Edit1.Text;

 

{ See if the field being search is a string field. If so, then pad the

quote string with quotation marks; otherwise, set it to a null value. }

 

if strField <> ’’ then

with Table1.FieldByName(strField) do

if (DataType = ftString) or (DataType = ftMemo) then

strQuote := ’"’ else

strQuote := ’’;

 

{ Construct the WHERE clause of the query based on the user’s choice

in Type. }

 

case etSQLOps(ComboBox1.ItemIndex) of

soNoCondition: strWhere := ’’;

soEqual: strWhere := strField + ’ = ’ + strQuote + strValue+ strQuote;

soNotEqual: strWhere := strField + ’ <> ’ + strQuote + strValue +

strQuote;

soLessThan: strWhere := strField + ’ < ’ + strQuote + strValue +

strQuote;

soLessEqual: strWhere := strField + ’ <= ’ + strQuote + strValue +

strQuote;

soMoreThan: strWhere := strField + ’ > ’ + strQuote + strValue +

strQuote;

soMoreEqual: strWhere := strField + ’ >= ’ + strQuote + strValue +

strQuote;

soStartsWith: strWhere := strField + ’ LIKE ’ + strQuote +

strValue + ’%’ + strQuote;

soNoStartsWith: strWhere := strField + ’ NOT LIKE ’ + strQuote +

strValue + ’%’ + strQuote;

soEndsWith: strWhere := strField + ’ LIKE ’ + strQuote +

’%’ + strValue + strQuote;

soNoEndsWith: strWhere := strField + ’ NOT LIKE ’ +

strQuote + ’%’ + strValue + strQuote;

soContains: strWhere := strField + ’ LIKE ’+ strQuote+’%’+ strValue

+ ’%’ + strQuote;

soNoContains: strWhere := strField + ’ NOT LIKE ’ + strQuote + ’%’

+ strValue + ’%’ + strQuote;

soBlank: strWhere := strField + ’ IS NULL’;

soNotBlank: strWhere := strField + ’ IS NOT NULL’;

end;

 

if ComboBox1.ItemIndex = Ord(soNoCondition) then

strQuery := ’SELECT * FROM "’ + strTable + ’"’

else if Table1.FieldByName(strField).DataType = ftString then

strQuery := ’SELECT * FROM "’ + strTable + ’" t WHERE t.’ + strWhere

else

strQuery := ’SELECT * FROM "’ + strTable + ’" t WHERE t.’ + strWhere;

 

{ Create an instance of the browser form. }

frmQuery := TResultForm.Create(Application);