插入查询语法

时间:2013-03-28 06:08:12

标签: c# sql sql-server sql-update sql-insert

我一直收到一个错误,说错误的语法靠近哪里。有人能告诉我我做错了什么吗?

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();
}

2 个答案:

答案 0 :(得分: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
        }
    }
}

答案 1 :(得分: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 + "')";