开发者

Remove the last comma in SQL UPDATE statement using StrUtils in Delphi

开发者 https://www.devze.com 2023-04-12 02:17 出处:网络
Assume that we have this SQL statement: UPDATE article SET saison=\'12E\', mode=\'ECH\', client=\'SAS\', WHERE ID=\'3448fe81-1bec-e011-8546-001f3ccf8f20\'

Assume that we have this SQL statement:

UPDATE article SET saison='12E', mode='ECH', client='SAS', WHERE ID='3448fe81-1bec-e011-8546-001f3ccf8f20'

This SQL 开发者_高级运维statement is generated by concatenated strings like this:

// saison change
procedure TarticleEditForm.saisonComboChange(Sender: TObject);
begin
    SQLQuery := SQLQuery + 'saison=''' + saisonCombo.Text + ''',';
end;

// client change
procedure TarticleEditForm.clientComboChange(Sender: TObject);
begin
    SQLQuery := SQLQuery + 'client=''' + clientCombo.Text + ''',';
end;
.
.
.

As you see, there is a comma before "WHERE" clause. How can I remove the last comma to have the correct statement:

UPDATE article SET saison='12E', mode='ECH', client='SAS' WHERE ID='3448fe81-1bec-e011-8546-001f3ccf8f20'

RMQ: the number of comma is not fixe, it can be 1, 2, 5...

thank you.

The solution is replacing ", WHERE" by "WHERE"

 SQLQuery := StringReplace(SQLQuery , ', WHERE', 'WHERE', [rfReplaceAll]);

I am using this to trace every change in HISTORY Table. Thank you all.


Rather than concatenating the changes to the SQL string as they happen, store them in a collection and build you SQL string after all the options have been evaluated.

Then you will know how many fields are going to be changed and build the statement correctly. Of course this will require you to store not only the value but also the name of the fild being changed:

[pseudo code]

for i=0 to fields_changed.count {
  sql = sql + fields_changed(i).field_name + " = " + fields_changed(i).new_value
  if i < fields_changed.count {
    sql = sql + ", "
  }
}
sql = sql + " WHERE ..."

EDIT: The other option you have is to simply perform a string replace on , WHERE with WHERE just before executing the statement; since the word 'where' is a reserved word and should not occur more than once in your SQL statement. This may be the simpler solution even if it feels like a bit of a hack.


another option is to reduce the length of the string by 1 character before appending the WHERE clause.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号