[英]Connection to SQL Server database
一個 .NET 應用程序,從中建立連接並按如下方式執行查詢(包裝在 try-catch 塊中):
using (SqlConnection conn = new SqlConnection(Configuration.connectionString))
{
SqlCommand cmd = new SqlCommand(createTransactionQuery,conn);
conn.Open();
return cmd.ExecuteNonQuery();
}
查詢字符串為:
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";
此代碼引發異常:
System.Exception: 'BEGIN' 附近的語法不正確。
我知道可以以更好的方式創建查詢字符串。 但是,我想知道問題的原因是什么,因為這個確切的查詢在 SQL Server Management Studio 本身中執行時是有效的。
我已經確保連接字符串是正確的,因為它在應用程序的不同部分完全正常工作。
你可以試試這個進行交易。 從您的代碼中刪除 first begin 和 last end 並按照以下說明操作:
BEGIN TRANSACTION trans
BEGIN TRY
--Do some insert or update
COMMIT TRANSACTION trans
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION trans
END CATCH
您在"COMMIT Transaction" + "END";
之間錯過了一個空格"COMMIT Transaction" + "END";
使用這個"COMMIT Transaction" + " END";
此外,您還沒有聲明varQuantity
並且在" VALUES (SYSDATETIME(),NULL,@varStaffID,@varProductID; "
之后錯過了一個封閉的括號" VALUES (SYSDATETIME(),NULL,@varStaffID,@varProductID; "
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.