【问题标题】:Specified cast is not valid for sql server query指定的强制转换对 sql server 查询无效
【发布时间】: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


    【解决方案1】:

    scope_identity() 返回一个小数(因为标识列不必是 int)。

    将其拆箱为小数,然后转换为 int:

    modified = (int)(decimal)cmd.ExecuteScalar();
    

    此外,您可以像这样插入到只有一个标识列的表中:

    insert [CMSCustom].[dbo].[sup_req_ids] default values;
    select scope_identity()
    

    【讨论】:

    • [掌心] 谢谢@Blorgbeard
    • SQL 2012 也有 sequences,它可以让您在没有表的情况下自动生成递增的 ID
    猜你喜欢
    • 2014-04-05
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多