C# 如何获取上次插入的id?
我有以下代码:C# 如何获取上次插入的id?,c#,sql,sql-server,C#,Sql,Sql Server,我有以下代码: string insertSql = "INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)"; using (SqlConnection myConnection = new SqlConnection(myConnectionString)) { myConnection.Open(); SqlCommand myCommand = new SqlCommand
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)";
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("@UserId", newUserId);
myCommand.Parameters.AddWithValue("@GameId", newGameId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
当我插入到这个表中时,我有一个名为gamesprofleiid
的自动递增int主键列,我如何才能得到最后一个插入的列,以便我可以使用该id插入到另一个表中?您可以创建一个
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)
然后执行intid=(int)命令
这将为您提供一些附加技术。对于SQL Server 2005+,如果没有insert触发器,则将insert语句(全部为一行,为清晰起见,此处拆分)更改为
对于SQL Server 2000,或者如果存在插入触发器:
INSERT INTO aspnet_GameProfiles(UserId,GameId)
VALUES(@UserId, @GameId);
SELECT SCOPE_IDENTITY()
然后
Int32 newId = (Int32) myCommand.ExecuteScalar();
我也有同样的需要,找到了这个答案
这将在公司表(comp)中创建一条记录,它将获取在公司表上创建的自动ID,并将其放入员工表(Staff)中,以便可以将两个表、多个员工链接到一个公司。它适用于我的SQL 2008数据库,应该适用于SQL 2005及以上版本
===========================
CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]
@comp_name varchar(55) = 'Big Company',
@comp_regno nchar(8) = '12345678',
@comp_email nvarchar(50) = 'no1@home.com',
@recID INT OUTPUT
--“@recID”用于保存我们即将获取的公司自动生成的ID号
AS
Begin
SET NOCOUNT ON
DECLARE @tableVar TABLE (tempID INT)
--上一行用于创建一个临时表,以保存自动生成的ID号供以后使用。它只有一个字段“tempID”,其类型INT与'@recID'相同
INSERT INTO comp(comp_name, comp_regno, comp_email)
OUTPUT inserted.comp_id INTO @tableVar
--上面的“输出插入。”行用于从正在创建的记录中的任何字段中获取数据。我们需要的数据是ID自动编号。因此,请确保它为您的表显示了正确的字段名,我的是“comp\u id”。然后将其放入我们前面创建的临时表中
VALUES (@comp_name, @comp_regno, @comp_email)
SET @recID = (SELECT tempID FROM @tableVar)
--上面的行用于搜索我们先前创建的临时表,其中保存了我们需要的ID。由于此临时表中只有一条记录和一个字段,因此它将只选择您需要的ID号并将其放入“@recID”中@recID'现在有了您想要的ID号,您可以按照您的意愿使用它,就像我在下面使用它一样
INSERT INTO staff(Staff_comp_id)
VALUES (@recID)
End
--好了。实际上,您可以在“插入的输出.WhatEverFieldNameYouWant”行中获取所需内容,并在临时表中创建所需字段并访问它以使用所需方式
很久以来,我一直在寻找类似的东西,有了这个详细的分类,我希望这能有所帮助 在纯SQL中,主语句如下所示:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[spCountNewLastIDAnyTableRows]
(
@PassedTableName as NVarchar(255),
@PassedColumnName as NVarchar(225)
)
AS
BEGIN
DECLARE @ActualTableName AS NVarchar(255)
DECLARE @ActualColumnName as NVarchar(225)
SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @PassedTableName
SELECT @ActualColumnName = QUOTENAME( COLUMN_NAME )
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = @PassedColumnName
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'select MAX('+ @ActualColumnName + ') + 1 as LASTID' + ' FROM ' + @ActualTableName
EXEC(@SQL)
END
INSERT INTO [simbs] ([En]) OUTPUT INSERTED.[ID] VALUES ('en')
方括号定义了表SIMB,然后是列En和ID,圆括号定义了要启动的列的枚举,然后是列的值,在我的例子中是一列和一个值。撇号括起一个字符串
我将向你解释我的方法:
这可能不容易理解,但我希望使用最后插入的id了解全局是有用的。当然,还有其他更简单的方法。但我有理由保留我的。不包括关联函数,只包括它们的名称和参数名称
我将这种方法用于医学人工智能
该方法检查中心表(1)中是否存在所需字符串。如果所需字符串不在中心表“simbs”中,或者如果允许重复,则将所需字符串添加到中心表“simbs”(2)中。最后插入的id用于创建关联表(3)
public List CreateSymbolByName(字符串SymbolName,bool AcceptDuplicates)
{
if(!AcceptDuplicates)//检查是否设置了“AcceptDuplicates”标志
{
List ExistentSymbols=GetSymbolByName(SymbolName,0,10);//创建包含现有记录的int数组列表
如果(ExistentSymbols.Count>0)返回ExistentSymbols;//(1)返回现有记录,因为不允许创建重复项
}
List ResultedSymbols=new List();//准备一个空列表
int[]symbolPosition={0,0,0,0};//为新符号准备一个中性位置
try//如果SQL失败,代码将继续执行catch语句
{
//默认值和空值不需要解释标识
string commandString=“INSERT INTO[simbs]([En])输出INSERTED.ID值(“+SymbolName+”);//在表“simbs”中的“En”列插入变量“SymbolName”存储的值
SqlCommand mySqlCommand=newsqlcommand(commandString,SqlServerConnection);//初始化查询环境
SqlDataReader myReader=mySqlCommand.ExecuteReader();//最后插入的ID作为第一行第一列上的任何结果集接收
int LastInsertedId=0;//如果插入成功,将更改此值
while(myReader.Read())//从结果集读取
{
if(myReader.GetInt32(0)>-1)
{
int[]symbolID=新的int[]{0,0,0,0};
LastInsertedId=myReader.GetInt32(0);/(2)获取上次插入的ID
symbolID[0]=LastInsertedId;//使用上次插入的id
if(symbolID[0]!=0 | | symbolID[1]!=0)//如果上次插入的id成功
{
结果符号。添加(符号d);
}
}
}
myReader.Close();
if(SqlTrace)SQLView.Log(mySqlCommand.CommandText);//记录命令的文本
if(LastInsertedId>0)//如果在表中插入新行成功
{
string commandString2=“UPDATE[simbs]SET[IR]=[ID]其中[ID]=“+LastInsertedId+”;;;;//通过向另一行提供上次插入的ID的值来更新表
SqlCommand mySqlCommand2=新的SqlCommand(commandString2,SqlServerConnection);
mySqlCommand2.ExecuteNonQuery();
INSERT INTO [simbs] ([En]) OUTPUT INSERTED.[ID] VALUES ('en')
public List<int[]> CreateSymbolByName(string SymbolName, bool AcceptDuplicates)
{
if (! AcceptDuplicates) // check if "AcceptDuplicates" flag is set
{
List<int[]> ExistentSymbols = GetSymbolsByName(SymbolName, 0, 10); // create a list of int arrays with existent records
if (ExistentSymbols.Count > 0) return ExistentSymbols; //(1) return existent records because creation of duplicates is not allowed
}
List<int[]> ResultedSymbols = new List<int[]>(); // prepare a empty list
int[] symbolPosition = { 0, 0, 0, 0 }; // prepare a neutral position for the new symbol
try // If SQL will fail, the code will continue with catch statement
{
//DEFAULT und NULL sind nicht als explizite Identitätswerte zulässig
string commandString = "INSERT INTO [simbs] ([En]) OUTPUT INSERTED.ID VALUES ('" + SymbolName + "') "; // Insert in table "simbs" on column "En" the value stored by variable "SymbolName"
SqlCommand mySqlCommand = new SqlCommand(commandString, SqlServerConnection); // initialize the query environment
SqlDataReader myReader = mySqlCommand.ExecuteReader(); // last inserted ID is recieved as any resultset on the first column of the first row
int LastInsertedId = 0; // this value will be changed if insertion suceede
while (myReader.Read()) // read from resultset
{
if (myReader.GetInt32(0) > -1)
{
int[] symbolID = new int[] { 0, 0, 0, 0 };
LastInsertedId = myReader.GetInt32(0); // (2) GET LAST INSERTED ID
symbolID[0] = LastInsertedId ; // Use of last inserted id
if (symbolID[0] != 0 || symbolID[1] != 0) // if last inserted id succeded
{
ResultedSymbols.Add(symbolID);
}
}
}
myReader.Close();
if (SqlTrace) SQLView.Log(mySqlCommand.CommandText); // Log the text of the command
if (LastInsertedId > 0) // if insertion of the new row in the table was successful
{
string commandString2 = "UPDATE [simbs] SET [IR] = [ID] WHERE [ID] = " + LastInsertedId + " ;"; // update the table by giving to another row the value of the last inserted id
SqlCommand mySqlCommand2 = new SqlCommand(commandString2, SqlServerConnection);
mySqlCommand2.ExecuteNonQuery();
symbolPosition[0] = LastInsertedId; // mark the position of the new inserted symbol
ResultedSymbols.Add(symbolPosition); // add the new record to the results collection
}
}
catch (SqlException retrieveSymbolIndexException) // this is executed only if there were errors in the try block
{
Console.WriteLine("Error: {0}", retrieveSymbolIndexException.ToString()); // user is informed about the error
}
CreateSymbolTable(LastInsertedId); //(3) // Create new table based on the last inserted id
if (MyResultsTrace) SQLView.LogResult(LastInsertedId); // log the action
return ResultedSymbols; // return the list containing this new record
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DBDemo2
{
public partial class Form1 : Form
{
string connectionString = "Database=company;Uid=sa;Pwd=mypassword";
System.Data.SqlClient.SqlConnection connection;
System.Data.SqlClient.SqlCommand command;
SqlParameter idparam = new SqlParameter("@eid", SqlDbType.Int, 0);
SqlParameter nameparam = new SqlParameter("@name", SqlDbType.NChar, 20);
SqlParameter addrparam = new SqlParameter("@addr", SqlDbType.NChar, 10);
public Form1()
{
InitializeComponent();
connection = new System.Data.SqlClient.SqlConnection(connectionString);
connection.Open();
command = new System.Data.SqlClient.SqlCommand(null, connection);
command.CommandText = "insert into employee(ename, city) values(@name, @addr);select SCOPE_IDENTITY();";
command.Parameters.Add(nameparam);
command.Parameters.Add(addrparam);
command.Prepare();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
int id = Int32.Parse(textBoxID.Text);
String name = textBoxName.Text;
String address = textBoxAddress.Text;
command.Parameters[0].Value = name;
command.Parameters[1].Value = address;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
int nid = Convert.ToInt32(reader[0]);
MessageBox.Show("ID : " + nid);
}
/*int af = command.ExecuteNonQuery();
MessageBox.Show(command.Parameters["ID"].Value.ToString());
*/
}
catch (NullReferenceException ne)
{
MessageBox.Show("Error is : " + ne.StackTrace);
}
catch (Exception ee)
{
MessageBox.Show("Error is : " + ee.StackTrace);
}
}
private void buttonSave_Leave(object sender, EventArgs e)
{
}
private void Form1_Leave(object sender, EventArgs e)
{
connection.Close();
}
}
}
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)SELECT SCOPE_IDENTITY()";
int primaryKey;
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("@UserId", newUserId);
myCommand.Parameters.AddWithValue("@GameId", newGameId);
primaryKey = Convert.ToInt32(myCommand.ExecuteScalar());
myConnection.Close();
}
var ContactID = db.GetLastInsertId();
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)
int id = (int)command.ExecuteScalar;
<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();
/*** Initialize and update Table Data Here ***/
/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();
//Update the Dataset
tblAdpt.Update(tblData);
//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;
cmd.ExecuteScalar();
result_id=cmd.LastInsertedId.ToString();