In Delphi 7, how do I escape a percent sign (%) in the Format function?
Question
I want to do something like this:
SQL.Text := Format('select foo from bar where baz like ''%s%''',[SearchTerm]);
But Format doesn't like that last '%', of course. So how can I escape it? \%
? %%
?
Or do I have to do this:
SQL.Text := Format('select foo from bar where baz like ''%s''',[SearchTerm+'%']);
?
Solution
Use another % in the format string:
SQL.Text := Format('select foo from bar where baz like ''%s%%''',[SearchTerm]);
OTHER TIPS
%% , IIRC.
Obligatory: http://xkcd.com/327/ :-)
Depending on context, your approach might be vulnerable to SQL injection. If the search term comes from user input it would probably be better to use a parameterized query or at least try to sanitize the input.
Add 2 percent sign to have 1 single %
Example :
Format('select foo from bar where baz like ''%%%s%%'',[SearchString])
Gives you
select foo from bar where baz like '%SearchString%'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow