简体   繁体   中英

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)))

(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.)

When I run the following SQL in Server Management Studio, I get exactly what I expect and want...

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...

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 ).

Unbox it as a decimal, then cast to 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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