【发布时间】:2014-03-28 00:04:13
【问题描述】:
我有一个 sql server 数据库,有两个字段(id (int, identity=yes), fake (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;
}
堆栈跟踪没有给我行号,所以我不确定这个错误来自哪里。
谁能帮忙解释我哪里出错了?
【问题讨论】:
标签: c# asp.net sql sql-server