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

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.

Related

how to write int value inside the query passing through asp.net

I am having the following exception when passing the query through executereader:
incorrect syntax near )"...
How do I write the 0 here?
Here's the whole query:
string query = "select distinct BillNumber,PatientName,MobileNo,DueAmount from PaymentView where RequestDate between '" + fromDate.ToString("yyyy-MM-dd") + "' and '" + toDate.ToString("yyyy-MM-dd") + "' and DueAmount>'"+value+"')";
Extra Closing bracket at end of query. Also DueAmount should not be wrap into single quotes remove it.
and DueAmount>'"+value+"')";
------------^
Note : This may lead to SQL Injection attack, My suggestion is use Sql Parameter.

Delphi 10 - SQL statement Syntax error Update

I have no idea whats wrong with my Code it keeps giving my an Synxtax error in UPDATE statement here is the code :
adoQueryUsers.SQL.Clear;
adoQueryUsers.SQL.Add('Update Users SET Password = "' +
EdtPassword.Text + '" where Username = "' + sUsername + '" ');
adoQueryUsers.Active := true;
adoQueryUsers.ExecSQL;
I did try using adoQueryUsers.SQL.Text : = but it gives me the exact same problem.
Remove your 'adoQueryUsers.Active := true;'. This is an update statement and don't return a recordset. Only your ExecSQL is needed.
Also, I would use parameters instead of parsing the password and user directly into the query or you're exposed to SQL injection
You have several issues in your code.
Let's start with the inappropriate call to
adoQueryUsers.Active := true;
You only use TADOQuery.Active or TADOQuery.Open on a SQL statement that returns a rowset. Your statement does not do so, so remove that statement. The TADOQuery.ExecSQL is the only one that is relevant here.
Next, stop trying to concatenate SQL, and use parameters instead. It's no more code and it properly handles things like quoting values, formatting dates, etc. It also prevents SQL injection issues for you.
adoQueryUsers.SQL.Clear;
adoQueryUsers.SQL.Add('Update Users SET Password = :Password')
adoQueryUsers.SQL.Add('Where UserName = :UserName');
adoQueryUsers.Parameters.ParamByName('Password').Value := EdtPassword.Text;
adoQueryUsers.Parameters.ParamByName('UserName').Value := sUserName;
adoQueryUsers.ExecSQL;

Matching text string on first letter in SQL query

SAMPLE CODE:
Dim sql As String = "SELECT * FROM " + tblName + " WHERE needsTranslation = 'True' AND dataText LIKE " & "'" & alpha & "%" & "'" & " ORDER BY dataText;"
da = New SqlDataAdapter(sql, strConnection)
OP:
I would like to create a SQL query that returns all records when the first letter of a string matches my variable. I am coding this in an ASP.net code behind page in vb.net.
SELECT * FROM " + tblName + " WHERE textData = ' & alpha & "
In this exmample textData is a string of text and alpha is a single letter a through z or A through Z.
I don't need the criteria to be case sensitive, but I do need only the first letter of textData to match alpha.
I have tested the LIKE comparator and it does not return all records that begin with alpha.
What is the best way to do this? Any and all help will be appreciated.
thanks again,
The LIKE operator is what you'd want to use, but you have to use the % wildcard character like so:
SELECT * FROM MyTable WHERE textData LIKE 'a%'
SQL has sub-string operator SUBSTR() or SUBSTRING()
select * from tableName where substr( textData ) in ( 'A', 'B', 'C', ... );
I couldn't add to the comments on one of the other posts, but I'll strongly second the need to use a parameterized query for these reasons (you can include usage of the like operator with the wildcard % like the other answer correctly summarized to answer your question):
It will protect you from making mistakes with single quotes, especially if the user enters a search string that includes them
(they will cause your query to fail).
It protects you from SQL injection exploits. Example, a user were able to input the value of the variable "alpha" in the above
example they could enter something like:
'; DELETE FROM ;
If the user you were using had excessive database rights, they could
wreak all kinds of havoc (or they could potentially get access to
data they shouldn't have access to).

SQL concatenation inside VBA string

I'm using VBA excel 2003,SQL 2005 to make a sql query call and inside my sql statement I'm using '+' operator to concatenate two strings.
dim query as string
query = "Select distinct ', '+emailaddress1 "
query = query & "from contact "
would this work inside vba? My query returns too many records in excel but not in SQL?
Please just focus on this 2 lines of code and not worry about the rest of my sql call, I'm just wondering whether or not this specific string would work?
Your code will return a column where each row would be an email address with a comma in front of it. If that is what you want, then yes, it will work.
If, on contrary, you want a single string where all email addresses would be listed, separated with commas, that'd be
query = "declare #foo varchar(max);"
query = query & "select distinct #foo = isnull(#foo,'') + emailaddress1 + ', ' from contact;"
query = query & "select left(#foo, len(#foo)-2);"

How do you put a carriage return into the field of an SQL statement using VB?

I want to insert a record using SQL and one of the fields needs to contain a carriage return, e.g.
Notes field:
Line 1
Line 2
End line
How would I code this SQL statement using VB
When you build the insert statement, you store it in a string somewhere. Add an escaped newline character into the string wherever you want the carrage returns to be.
A simple way to do that in VB would be:
Sql = Sql & vbCrLf
Using SQL code:
UPDATE MyTable
SET MyCol = MyCol + CHAR(13) + CHAR(10);