Skip to main content
 首页 » 编程设计

c#之指定的转换对于 sql server 查询无效

2024年02月13日13Leo_wl

我有一个包含两个字段的 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; 
} 

堆栈跟踪没有给我行号,所以我不确定这个错误是从哪里来的。

任何人都可以帮助解释我哪里出错了吗?

请您参考如下方法:

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

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

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

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

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