0

我不断收到错误消息,提示 where 附近的语法不正确。有人可以告诉我我做错了什么吗?

string strSession = objGetSession.GetEmailFromSession();
con.Open();
string strInsertFnLn = "Insert into AUserAddress (FirstName, LastName) values (@FirstName, @LastName) where AUser_ID = (Select ID from AUser where Email ='" + strSession + "')";

using (SqlCommand Cmd = new SqlCommand(strInsertFnLn, con))
{
    Cmd.Parameters.AddWithValue("@FirstName", txtEditFirstName.Text);
    Cmd.Parameters.AddWithValue("@LastName", txtEditLastName.Text);
    //Cmd.Parameters.AddWithValue("@Email", txtEditEmail.Text);
    Cmd.ExecuteNonQuery();
    con.Close();
}
4

2 回答 2

2

我猜你的意思是UPDATE

UPDATE  a
SET     a.FirstName = @FirstName,
        a.LastName = @LastName
FROM    AUserAddress a
        INNER JOIN AUser b
            ON a.AUser_ID = b.ID
WHERE   b.Email = @Email

所以完整的声明看起来像这样,

string strSession = objGetSession.GetEmailFromSession();            
string connString = "connection string here";
string strInsertFnLn = @"
                            UPDATE  a
                            SET     a.FirstName = @FirstName,
                                    a.LastName = @LastName
                            FROM    AUserAddress a
                                    INNER JOIN AUser b
                                        ON a.AUser_ID = b.ID
                            WHERE   b.Email = @Email
                        ";
using (SqlConnection con = new SqlConnection(connString))
{
    using (SqlCommand Cmd = new SqlCommand(strInsertFnLn, con))
    {
        Cmd.Parameters.AddWithValue("@FirstName", txtEditFirstName.Text);
        Cmd.Parameters.AddWithValue("@LastName", txtEditLastName.Text);
        Cmd.Parameters.AddWithValue("@Email", strSession);
        try
        {
            con.Open();
            Cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            // do something with the exception
            // don't hide it
        }
    }
}
于 2013-03-28T06:10:19.470 回答
1

问题出在这条线上

string strInsertFnLn = "Insert into AUserAddress (FirstName, LastName) 
   values (@FirstName, @LastName) where 
   AUser_ID = (Select ID from AUser where Email ='" + strSession + "')";

where这个查询中的条件有什么用
应该是这样的

string strInsertFnLn = "Insert into AUserAddress (FirstName, LastName) 
                            values (@FirstName, @LastName)";

编辑 1

或者,如果您想更新记录,则应如下所示

 string strInsertFnLn = "update AUserAddress set FirstName=@FirstName, 
                       LastName=@LastName where 
   AUser_ID = (Select ID from AUser where Email ='" + strSession + "')";
于 2013-03-28T06:11:03.473 回答