[英]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.