我正在尝试获取最近插入的表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?
答案 0 :(得分:0)
好的,我明白了。而不是使用SET我在InsertQuery中使用了SELECT:
INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (@OrderDate, @OrderTotal, @OrderAccount, @OrderCostCentre); SELECT @OrderNewID = SCOPE_IDENTITY()