0

I am having a small issue with SqlServerCe. When using the below sqlString to perform a ExecuteNonQuery(); command I get the error below.

string sqlString = "INSERT INTO Images (UID, Name) " +
            "VALUES ((SELECT ID FROM Contributors WHERE ID = @UID), @Name);";

gives this error:

There was an error parsing the query. [ Token line number = 1,Token line offset = 41,Token in error = SELECT ]

Any suggestions?

Method

public static void InsertImage(Contributor contObj, string ImageName)
{
    string sqlString = "INSERT INTO Images (UID, Name) " +
        "VALUES ((SELECT ID FROM [Contributors] WHERE ID = @UID), @Name);";
    using (SqlCeConnection sqlConnection =
        new SqlCeConnection(WebConfigurationManager.ConnectionStrings["DefaultSQL"].ConnectionString))
    {
        SqlCeCommand sqlCommand = new SqlCeCommand(sqlString, sqlConnection);
        sqlCommand.Parameters.AddWithValue("@UID", contObj.ID);
        sqlCommand.Parameters.AddWithValue("@Name", ImageName);
        sqlConnection.Open();
        sqlCommand.ExecuteNonQuery();
        sqlConnection.Close();
    }
}
4

3 回答 3

2

为什么在这里使用嵌套选择?由于@UID已经引用了您选择的 ID 列,您不能这样做:

INSERT INTO Images (UID, Name) 
VALUES (@UID, @Name)

如果您真的必须使用选择,请查看 bluefeet 的答案。他提供了您指定的参数 ( @Name) 作为要插入的值之一,所以没问题。

于 2012-05-21T18:48:55.863 回答
1

你会想要使用INSERT INTO...SELECT..FROM

string sqlString = "INSERT INTO Images (UID, Name) " +
            "SELECT ID, @Name FROM Contributors WHERE ID = @UID;";

如果您已经知道 的值@ID,那么您可以使用INSERT INTO... VALUES...查询

INSERT INTO Images (UID, Name)
VALUES (@UID, @Name)

编辑,这是您的更新查询代码

public static void InsertImage(Contributor contObj, string ImageName)
{
    string sqlString = "INSERT INTO Images (UID, Name) " +
        "VALUES (@UID, @Name)";
    using (SqlCeConnection sqlConnection =
        new SqlCeConnection(WebConfigurationManager.ConnectionStrings["DefaultSQL"].ConnectionString))
    {
        SqlCeCommand sqlCommand = new SqlCeCommand(sqlString, sqlConnection);
        sqlCommand.Parameters.AddWithValue("@UID", contObj.ID);
        sqlCommand.Parameters.AddWithValue("@Name", ImageName);
        sqlConnection.Open();
        sqlCommand.ExecuteNonQuery();
        sqlConnection.Close();
    }
}
于 2012-05-21T18:46:08.877 回答
0

你可以这样做:

string sqlString = @"INSERT INTO Images(UID, Name)
                     SELECT ID, @Name
                     FROM Contributors
                     WHERE ID = @UID"
于 2012-05-21T18:51:06.673 回答