我对SqlServerCe有一个小问题。 当使用下面的sqlString来执行ExecuteNonQuery();命令我得到以下错误。
string sqlString = "INSERT INTO Images (UID, Name) " +
"VALUES ((SELECT ID FROM Contributors WHERE ID = @UID), @Name);";
给出了这个错误:
There was an error parsing the query. [ Token line number = 1,Token line offset = 41,Token in error = SELECT ]
有什么建议吗?
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();
}
}
答案 0 :(得分:2)
为什么在这里使用嵌套选择?由于@UID
已经引用了您选择的ID列,因此您不能这样做:
INSERT INTO Images (UID, Name)
VALUES (@UID, @Name)
如果你真的必须使用一个选择,那么看看bluefeet的答案。他将您指定的参数(@Name
)作为插入的值之一提供,所以没问题。
答案 1 :(得分: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();
}
}
答案 2 :(得分:0)
你可以这样做:
string sqlString = @"INSERT INTO Images(UID, Name)
SELECT ID, @Name
FROM Contributors
WHERE ID = @UID"