简体   繁体   English

指定的强制转换对SQL Server查询无效

[英]Specified cast is not valid for sql server query

I have an sql server database with two fields (id (int, identity=yes), fake (char(10))) 我有一个具有两个字段的SQL Server数据库(ID(整数(int,identity = yes),假(char(10))))

(The "fake" field is there because I couldn't work out how to get only a new id value without inserting something into another column first. Ultimately all I want is an incremental, unique id.) (存在“假”字段,因为我无法弄清楚如何在不先将内容插入另一列的情况下仅获取新的id值。最终,我想要的只是一个递增的唯一ID。)

When I run the following SQL in Server Management Studio, I get exactly what I expect and want... 当我在Server Management Studio中运行以下SQL时,我得到的正是我期望和想要的...

INSERT INTO [CMSCustom].[dbo].[sup_req_ids](fake) VALUES ('a'); SELECT SCOPE_IDENTITY()

When I run the following c# code in my ASP.NET page, it gives me a "Specified cast is not valid" error... 当我在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;
}

The stack trace isn't giving me a line number so I'm not sure where this error is coming from. 堆栈跟踪没有给我一个行号,所以我不确定这个错误是从哪里来的。

Can anyone help explain where I'm going wrong? 谁能帮我解释我要去哪里错了?

scope_identity() returns a decimal (because identity columns don't have to be int ). scope_identity()返回一个十进制数(因为标识列不必是int )。

Unbox it as a decimal, then cast to int: 取消装箱为小数,然后转换为int:

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

Also, you can insert into a table with only an identity column like this: 此外,您可以将插入的表仅包含一个标识列,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM