有一个问题:关键字“ as”附近的语法不正确

时间:2019-06-21 07:43:52

标签: sql sql-server

错误:

  

键盘“ as”附近的语法不正确。

代码:

private void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            string str_connection = "Data Source = MSSQLServer058; Initial Catalog = CarRental; Integrated Security = True";
            string MyUpd = "Update [dbo].[Booking] as t1, Car as t2, Customer as t3 " +
                           "set t1.[CustomerID] = '" + lblCustomerID.Text + "'," +
                           "t1.[VIN] = '" + lblVIN.Text + "'," +
                                "t3.[DriverLicNo] = '" + DriverLicNotxt.Text + "'" +
                           "t2.[Make] = '" + txtMake.Text + "'" +

            MessageBox.Show("Save Complete!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
}

2 个答案:

答案 0 :(得分:2)

好像您要尝试一次更新多个表-这是不可能的。

更改SQL以进行多次更新(如果需要),将其封装在事务中:

BEGIN TRAN
UPDATE [dbo].[Booking] set ...
UPDATE Car ...
UPDATE Customer ...
COMMIT TRAN

答案 1 :(得分:1)

在提供C#答案时,我总是要告诫:我不是 C#开发人员。我真的很少有经验。我所做的就是在向他人展示如何对查询进行参数化时,我总是做的事情,我检查了documentation

private void btnUpdate_Click(object sender, EventArgs e)
{
    string str_connection = "Data Source = MSSQLServer058; Initial Catalog = CarRental; Integrated Security = True";

    using (SqlConnection conn = new SqlConnection(str_connection))
    {

        //Do your queries really have no WHERE?
        string MyUpd = "UPDATE dbo.Booking SET CustomerID = @CustomerID, VIN = @VIN; " +
                        "UPDATE dbo.Car SET Make = @Make; " + 
                        "UPDATE dbo.Customer SET DriverLicNo = @LicNo;";

        using (SqlCommand comm = new SqlCommand(MyUpd,conn))
        {

            comm.Parameters.Add("@CustomerID",SqlDbType.Int).Value = lblCustomerID.Text; //Guessed data type
            comm.Parameters.Add("@VIN",SqlDbType.VarChar,50).Value = lblVIN.Text; //Guessed data type
            comm.Parameters.Add("@Make",SqlDbType.VarChar,50).Value = txtMake.Text; //Guessed data type
            comm.Parameters.Add("@DriverLicNo",SqlDbType.VarChar,50).Value = DriverLicNotxt.Text; //Guessed data type

            try
            {
                conn.Open();
                comm.ExecuteNonQuery();
                MessageBox.Show("Save Complete!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                /* Your Error handling */
            }
        }
    }
}

对于那些绝对有C#经验的人,如果有任何问题,请发表评论,我将很乐意进行修复(或提交修改)。希望至少,这可以使OP步入正轨。