[英]Specified cast is not valid for sql server query
我有一个具有两个字段的SQL Server数据库(ID(整数(int,identity = yes),假(char(10))))
(存在“假”字段,因为我无法弄清楚如何在不先将内容插入另一列的情况下仅获取新的id值。最终,我想要的只是一个递增的唯一ID。)
当我在Server Management Studio中运行以下SQL时,我得到的正是我期望和想要的...
INSERT INTO [CMSCustom].[dbo].[sup_req_ids](fake) VALUES ('a'); SELECT SCOPE_IDENTITY()
当我在ASP.NET页面中运行以下c#代码时,它给我“指定的转换无效”错误...
protected int insertRequest()
{
int modified = 0;
string sql = "Insert into sup_req_ids (fake) Values('a');SELECT SCOPE_IDENTITY()";
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["Ektron.CMSCustom"].ToString();
using(SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
modified = (int)cmd.ExecuteScalar();
}
catch (Exception e)
{
Response.Write(e.Message);
Response.Write(e.StackTrace);
Response.Write(e.Source);
}
}
return modified;
}
堆栈跟踪没有给我一个行号,所以我不确定这个错误是从哪里来的。
谁能帮我解释我要去哪里错了?
scope_identity()返回一个十进制数(因为标识列不必是int
)。
取消装箱为小数,然后转换为int:
modified = (int)(decimal)cmd.ExecuteScalar();
此外,您可以将插入的表仅包含一个标识列,如下所示:
insert [CMSCustom].[dbo].[sup_req_ids] default values;
select scope_identity()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.