簡體   English   中英

指定的強制轉換對SQL Server查詢無效

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

我有一個具有兩個字段的SQL Server數據庫(ID(整數(int,identity = yes),假(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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM