使用内部联接执行SQL更新

时间:2015-02-16 03:38:09

标签: c# mysql sql sql-server

我正在尝试使用另一个表的内部联接来更新用户表中的字段,但它似乎不起作用。我使用下面的代码:

        SqlCommand cmd = new SqlCommand("UPDATE U SET User.firstname = @Firstname FROM dbo.User AS U INNER JOIN dbo.Driver AS D ON U.userid = D.driverid WHERE D.driverid = @Driverid");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;
        cmd.Parameters.Add("@Firstname", SqlDbType.VarChar, 50).Value = firstname;
        cmd.Parameters.Add("@Driverid", SqlDbType.VarChar, 50).Value = driverid;
        conn.Open();
        cmd.ExecuteNonQuery();

SQL:

UPDATE
  U 
SET 
  User.firstname = @Firstname 
FROM 
  dbo.User AS U 
  INNER JOIN dbo.Driver AS D ON 
    U.userid = D.driverid 
WHERE
  D.driverid = @Driverid

我收到以下错误:

System.Web.Services.Protocols.SoapException:服务器无法处理请求。 ---> System.Data.SqlClient.SqlException:关键字'用户'

附近的语法不正确

我哪里可能出错?感谢

1 个答案:

答案 0 :(得分:0)

User在您的选择部分中定义/别名为U,因此在更新字段列表中将其引用为U

<强> EDITED : 在User周围添加了方括号,它似乎是一个保留的SQL关键字。

UPDATE
  U 
SET 
  U.firstname = @Firstname 
FROM 
  dbo.[User] AS U 
  INNER JOIN dbo.Driver AS D ON 
    U.userid = D.driverid 
WHERE
  D.driverid = @Driverid