我在以下msdn主题中看到过这种类型的UPDATE语句(就像插入语句一样):
http://msdn.microsoft.com/en-us/library/aa0416cz.aspx#Y2461
更新声明: -
adapter.UpdateCommand = New SqlCommand("UPDATE Customers " &
"(CustomerID, CompanyName) VALUES(@CustomerID, @CompanyName) " & _
"WHERE CustomerID = @oldCustomerID AND CompanyName = " &
"@oldCompanyName", connection)
这个陈述是否正确?
我尝试过执行它,但是它会出现语法错误。
答案 0 :(得分:6)
不,应该是:
UPDATE Customers
SET
CustomerID = @CustomerID,
CompanyName = @CompanyName
WHERE
CustomerID = @oldCustomerID AND
CompanyName = @oldCompanyName
或者要完成示例代码,它应该是:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName WHERE CustomerID = @oldCustomerID AND CompanyName = @oldCompanyName", connection)
以下是您和此情况的另一个参考:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx
答案 1 :(得分:3)
对于INSERT INTO
而言,SQL似乎是正确的,而对于UPDATE
则不正确它应该是:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers" & _
" SET CustomerID = @CustomerID, CompanyName = @CompanyName)" & _
" WHERE CustomerID = @oldCustomerID AND CompanyName =" & _
" @oldCompanyName", connection)
SQL就是人们称之为paramaterized的东西,因此这段代码(在代码片段中较低)非常重要:
adapter.UpdateCommand.Parameters.Add( _
"@CustomerID", SqlDbType.NChar, 5, "CustomerID")
adapter.UpdateCommand.Parameters.Add( _
"@CompanyName", SqlDbType.NVarChar, 30, "CompanyName")
' Pass the original values to the WHERE clause parameters.
Dim parameter As SqlParameter = dataSet.UpdateCommand.Parameters.Add( _
"@oldCustomerID", SqlDbType.NChar, 5, "CustomerID")
parameter.SourceVersion = DataRowVersion.Original
parameter = adapter.UpdateCommand.Parameters.Add( _
"@oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName")
parameter.SourceVersion = DataRowVersion.Original
答案 2 :(得分:2)
据我所知,语法无效。以下内容为Incorrect syntax near '('.
我建议按照Dan's answer进行更改。
CREATE TABLE Customers
(
CustomerID INT,
CompanyName VARCHAR(10)
)
DECLARE
@CustomerID INT,
@CompanyName VARCHAR(10),
@oldCustomerID INT,
@oldCompanyName VARCHAR(10)
UPDATE Customers (CustomerID, CompanyName)
VALUES(@CustomerID, @CompanyName)
WHERE CustomerID = @oldCustomerID AND CompanyName = @oldCompanyName