在SQL INSERT命令期间/之后返回标识列的值

Ada*_*ane 0 .net c# sql-server

使用VS 2010,ASP.NET,.NET 3.0和C#...

当我使用System.Web.UI.WebControls.SqlDataSource并调用其Insert()方法插入一个新行,并且该表有一个标识列时,我希望我的方法返回该列的值.

例如,在我的SQL 2005表中,我得到了:

  • 顾客ID
  • Customer.FirstName
  • Customer.LastName

Customer.Id是身份列.

当我调用我的方法InsertNewCustomerRecord("John","Smith")时,我希望能够返回在数据库中自动生成的Customer.Id.

对不起这个粗略提出的问题.如果我能添加更好的细节,请告诉我.谢谢.

Tho*_*mas 5

如果您使用的是SQL Server 2005或更高版本,则可以使用以下OUTPUT子句在单个语句中执行此操作:

Create Table Foo    (
                    Id int not null identity(1,1)
                    , Name varchar(50) null
                    , ....
                    )

Insert Foo(Name)
    Output inserted.Id, inserted.Name
Select 'Foo'
Union All Select 'Bar'
....
Run Code Online (Sandbox Code Playgroud)

如果您使用的是SQL Server 2000,那么您应该这样使用SCOPE_IDENTITY:

Insert Foo(Name)
Select 'Foo'

Select SCOPE_IDENTITY()
Run Code Online (Sandbox Code Playgroud)

请注意,我只能使用此方法一次执行一次插入,因为我们希望SCOPE_IDENTITY在Insert语句之后立即调用.

如果您使用的是SQL Server 2000之前的版本,则需要使用 @@IDENTITY

Insert Foo(Name)
Select 'Foo'

Select @@Identity
Run Code Online (Sandbox Code Playgroud)

问题是,如果您在桌面上有触发器,@@ Identity将会做一些时髦的事情.

编辑你问过如何在C#中使用这些信息.您可以像调用SELECT查询一样使用它:

var connString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
DataTable newData;

using ( var conn = new SqlConnection( connString ) )
{
    conn.Open();
    const string sql = "Insert Foo(Name) Output inserted.Id, inserted.Name Values(@Name)";
    using ( var cmd = new SqlCommand( sql, conn ) )
    {
        cmd.Parameters.AddWithValue("@Name", "bar");
        using ( var da = new SqlDataAdapter( cmd ) )
        {
            da.Fill( newData );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我假设您在配置文件中有connectionStringsMyConnectionStringName 的条目.此外,您还需要添加引用System.Configuration才能使用ConfigurationMananager该类.我没有检查这段代码,但它应该非常接近你需要的.在这种情况下,我正在直接编写查询.还有其他解决方案,例如使用DataSource控件和设置SelectCommand.