当试图获取插入的ID时,强制转换无效

本文关键字:转换 无效 ID 获取 插入 | 更新日期: 2023-09-27 17:49:41

我试图为表抓取最近插入的ID,但我一直收到一个转换错误。项目总是包含NULL,我不知道为什么。我正在遵循以下说明:http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most-recently-added-record

下面是我的SqlDataSource:
<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
    ConnectionString="<%$ ConnectionStrings:NH_SWAGConnectionString %>"             
    InsertCommand="INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (@OrderDate, @OrderTotal, @OrderAccount, @OrderCostCentre); SET @OrderNewID = SCOPE_IDENTITY()" 
    SelectCommand="SELECT * FROM [tblOrders]" 
    UpdateCommand="UPDATE [tblOrders] SET [OrderDate] = @OrderDate, [OrderTotal] = @OrderTotal, [OrderAccount] = @OrderAccount, [OrderCostCentre] = @OrderCostCentre WHERE [OrderID] = @original_OrderID AND [OrderDate] = @original_OrderDate AND [OrderTotal] = @original_OrderTotal AND [OrderAccount] = @original_OrderAccount AND [OrderCostCentre] = @original_OrderCostCentre"            
    ConflictDetection="CompareAllValues" 
    OldValuesParameterFormatString="original_{0}"
    OnInserting="SqlDataSource2_Inserting"
    OnInserted="SqlDataSource2_Inserted">
    <InsertParameters>
        <asp:Parameter Direction="Output" Name="OrderNewId" Type="Int32" />
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="OrderDate" Type="DateTime" />
        <asp:Parameter Name="OrderTotal" Type="Decimal" />
        <asp:Parameter Name="OrderAccount" Type="String" />
        <asp:Parameter Name="OrderCostCentre" Type="String" />
        <asp:Parameter Name="original_OrderID" Type="Int32" />
        <asp:Parameter Name="original_OrderDate" Type="DateTime" />
        <asp:Parameter Name="original_OrderTotal" Type="Decimal" />
        <asp:Parameter Name="original_OrderAccount" Type="String" />
        <asp:Parameter Name="original_OrderCostCentre" Type="String" />
    </UpdateParameters>
</asp:SqlDataSource>

下面是插入新记录的代码,并调用SCOPE_IDENTITY()来获取新ID:

protected void btnOrder_Click(object sender, EventArgs e)
{
    //Add entry to Order Table    
    SqlDataSource2.InsertParameters.Add("OrderDate", DateTime.Now.ToString("MMMM dd, yyyy"));
    SqlDataSource2.InsertParameters.Add("OrderTotal", "0");
    SqlDataSource2.InsertParameters.Add("OrderAccount", ItmUser);
    SqlDataSource2.InsertParameters.Add("OrderCostCentre", ItmCostCode.Text);
    SqlDataSource2.Insert();
}
protected void SqlDataSource2_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
    OrderNewID = (int)e.Command.Parameters["@OrderNewId"].Value;
}

为什么上面的@OrderNewId是NULL?

当试图获取插入的ID时,强制转换无效

好吧,我明白了。我在InsertQuery:

中使用SELECT而不是SET。
INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (@OrderDate, @OrderTotal, @OrderAccount, @OrderCostCentre); SELECT @OrderNewID = SCOPE_IDENTITY()