我有一个接受各种数据(通过文本框和检查框列表)的表单,在单击事件时,它们将所有数据插入到一个表中,并选择scope_identity,然后将其存储在一个变量中,以便通过循环到另一个表中来使用它来插入检查框列表项
根据许多答案和示例,这应该可以完美地工作!..but它给了我这个错误:
Exception Details: System.InvalidCastException: Specified cast is not valid.
Line 66: int NewBrandId = (int)comm.ExecuteScalar();
这是我的linkbutton方法代码:
protected void lnkbtnUploadAndSubmit_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MOODbCenterConnection"].ConnectionString);
SqlCommand comm = new SqlCommand("INSERT INTO Brands (BrandName, BrandLogo, BrandWebsite, IsBrandVisible) VALUES (@Name, @Logo, @Website, @IsVisible); SELECT scope_identity();", conn);
comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 50);
comm.Parameters["@Name"].Value = txtbxBrandName.Text;
comm.Parameters.Add("@Logo", System.Data.SqlDbType.Text);
comm.Parameters["@Logo"].Value = fileuploadLogo.PostedFile.FileName;
comm.Parameters.Add("@Website", System.Data.SqlDbType.Text);
comm.Parameters["@Website"].Value = txtbxWebsite.Text;
comm.Parameters.Add("@IsVisible", System.Data.SqlDbType.Bit);
comm.Parameters["@IsVisible"].Value = chkbxIsPublished.Checked;
conn.Open();
int NewBrandId = (int)comm.ExecuteScalar();
conn.Close();
foreach (ListItem li in chkbxlstCuisines.Items)
{
if (li.Selected)
{
conn.Open();
SqlCommand comm2 = new SqlCommand("INSERT INTO BrandCuisines (CuisineId, BrandId) VALUES (@CuisineId, @NewBrandId)", conn);
comm2.Parameters.Add("@CuisineId", System.Data.SqlDbType.Int);
comm2.Parameters["@CuisineId"].Value = li.Value;
comm2.Parameters.Add("@NewBrandId", System.Data.SqlDbType.Int);
comm2.Parameters["@NewBrandId"].Value = NewBrandId;
comm2.ExecuteNonQuery();
conn.Close();
}
}
}
奇怪的编辑当我直接在visual studio的sql server express中运行它时,查询运行得很好!
这个奇怪问题的奇怪解释
alexb的第一个解决方案:
我做到了:)我的sql server2008返回打包到‘System.Decimal’中的对象。尝试使用System.Convert.ToInt32而不是cast。
Example : int NewBrandId = System.Convert.ToInt32(comm.ExecuteScalar());
我的第二个解决方案:
没有使用"SELECT scope_identity();“,而是使用了"SELECT BrandId FROM Brands WHERE BrandId = @@Identity;”,它为您提供了更多的控制,但我个人更倾向于第一种解决方案
注意:"SELECT @@Identity;“也可以正常工作
谢谢大家,我希望它能帮助其他人!
发布于 2010-12-11 04:54:58
comm.ExecuteScalar()
到底返回了什么?也许它会返回打包到object
中的long
或double
。
记不清了,但似乎我在1-2年前就遇到过一些事情。
发布于 2011-04-04 04:25:21
如果可以更改SQL,一种更简单的方法是
SELECT CONVERT(int, SCOPE_IDENTITY())
发布于 2013-10-30 22:15:19
正如Dimi所说,Identity是一个SQL数字(.NET小数)。这应该是可行的:
decimal decimalBrandId = (decimal)comm.ExecuteScalar();
int NewBrandId = (int)decimalBrandId;
https://stackoverflow.com/questions/4413178
复制相似问题