Reputation: 576
A .NET application, from which a connection is being made and query executed as follows (wrapped in a try-catch block):
using (SqlConnection conn = new SqlConnection(Configuration.connectionString))
{
SqlCommand cmd = new SqlCommand(createTransactionQuery,conn);
conn.Open();
return cmd.ExecuteNonQuery();
}
The query string is:
createTransactionQuery = "BEGIN " +
"BEGIN Transaction" +
" BEGIN TRY " +
" --variables" +
" DECLARE @varStaffID int;" +
" DECLARE @varProductID int;" +
" SET @varStaffID = " + transaction.getStaff().getID() + ";" +
" SET @varProductID = " + transaction.getProduct().getProductID() + ";" +
" " +
" --New record in Transactions table " +
" INSERT INTO Transactions (Timestamp_, CustomerID, StaffID, ProductID) " +
" VALUES (SYSDATETIME(),NULL,@varStaffID,@varProductID; " +
" " +
" --Update inventory (Products table)" +
" --First retrieve the current quantity of this product" +
" DECLARE @varCurrQuantity int; " +
" SET @varCurrQuantity = (SELECT Quantity FROM Products WHERE ProductID=@varProductID); " +
" --and update it" +
" UPDATE Products " +
" SET Quantity = @varQuantity-1 " +
" WHERE ProductID = @varProductID; " +
" END TRY " +
" BEGIN CATCH " +
" ROLLBACK Transaction " +
" END CATCH " +
"COMMIT Transaction" +
"END";
This code throws an exception:
System.Exception: Incorrect syntax near 'BEGIN'.
I know that the query string could be created in a better way. However, I want to know what the cause of the problem is, as this exact query is working when it is executed within SQL Server Management Studio itself.
I have made sure the connection string is correct, as it is working exactly as it should in a different part of the application.
Upvotes: 0
Views: 91
Reputation: 1
You have missed a space between "COMMIT Transaction" + "END";
use this "COMMIT Transaction" + " END";
Also you have not declared varQuantity
and missed a closed bracket after
" VALUES (SYSDATETIME(),NULL,@varStaffID,@varProductID; "
Upvotes: 0
Reputation: 39966
It seems you have a missing close parenthesis here:
VALUES (SYSDATETIME(),NULL,@varStaffID,@varProductID; "
However this kind of string concatenation are open to SQL Injection attacks. You should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
To learn how to use parameterized queries, see an example below:
https://stackoverflow.com/a/50597820/2946329
Upvotes: 2
Reputation: 601
you can try this for a transaction. remove first begin and last end from you code and follow this instruction:
BEGIN TRANSACTION trans
BEGIN TRY
--Do some insert or update
COMMIT TRANSACTION trans
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION trans
END CATCH
Upvotes: 0