programing

마지막으로 삽입된 ID를 얻는 방법

starjava 2023. 4. 7. 20:49
반응형

마지막으로 삽입된 ID를 얻는 방법

코드는 다음과 같습니다.

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();
}

이이 있습니다.이 컬럼에는 auto_increment int primary key primary key는 auto_increment int primary key입니다.GamesProfileId이 ID를 사용하여 다른 테이블에 삽입할 수 있도록 하기 위해 이 다음에 마지막으로 삽입한 것을 어떻게 하면 좋을까요?

SQL Server 2005+의 경우 삽입 트리거가 없는 경우 insert 문을 다음과 같이 변경합니다(명확하게 하기 위해 한 줄 모두 분할).

INSERT INTO aspnet_GameProfiles(UserId,GameId)
OUTPUT INSERTED.ID
VALUES(@UserId, @GameId)

SQL Server 2000의 경우 또는 삽입 트리거가 있는 경우:

INSERT INTO aspnet_GameProfiles(UserId,GameId) 
VALUES(@UserId, @GameId);
SELECT SCOPE_IDENTITY()

그리고 나서.

 Int32 newId = (Int32) myCommand.ExecuteScalar();

SqlCommand를 생성할 수 있습니다.CommandText to와

INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)

를 실행합니다.int id = (int)command.ExecuteScalar.

MSDN 기사에서는 몇 가지 추가 기술에 대해 설명합니다.

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();
}

이거면 될 거야.

나도 같은 욕구가 있었고 이 답을 찾았다.

그러면 회사 테이블(comp)에 레코드가 작성되고,는 회사 테이블에서 작성된 자동 ID를 잡아 Staff 테이블(스태프)에 드롭합니다.이것에 의해, 2개의 테이블을 링크 할 수 있습니다.많은 직원이 1개의 회사에 소속됩니다.SQL 2008 DB에서 작동하며 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 번호를 유지하는 임시 테이블을 만드는 데 사용됩니다.'temp' 필드가 하나뿐입니다.ID' 및 그 유형 INT는 '@recID'와 동일합니다.

  INSERT INTO comp(comp_name, comp_regno, comp_email) 

  OUTPUT inserted.comp_id INTO @tableVar

-- 위의 'OUTPUT inserted.' 행은 현재 작성 중인 레코드의 모든 필드에서 데이터를 가져올 때 사용됩니다.우리가 원하는 이 데이터는 아이디 autonumber입니다.테이블의 올바른 필드명이 기재되어 있는 것을 확인해 주세요.제 이름은 'comp_id'입니다.그런 다음 이전에 작성한 임시 테이블로 떨어집니다.

  VALUES (@comp_name, @comp_regno, @comp_email)

  SET @recID = (SELECT tempID FROM @tableVar)

-- 위의 행은 이전에 작성한 임시 테이블을 검색할 때 사용합니다.이 테이블은 필요한 ID가 저장되어 있습니다.이 임시 테이블에는 레코드가 1개뿐이고 필드도 1개뿐이므로 필요한 ID 번호만 선택하여 '@recID'로 드롭합니다.@recID'는 이제 당신이 원하는 ID 번호를 가지고 있으며, 당신은 내가 아래에 사용했듯이 당신이 원하는 ID 번호를 사용할 수 있습니다.

  INSERT INTO staff(Staff_comp_id) 
  VALUES (@recID)

 End

자, 여기 있습니다.'OUTPUT'삽입된 내용을 원하는 대로 가져올 수 있습니다.WhatEverFieldNameYouWant' 행을 사용하여 임시 테이블에서 원하는 필드를 만들고 원하는 대로 사용할 수 있도록 액세스합니다.

오랫동안 이런 걸 찾고 있었는데, 이렇게 자세히 분석했으니까 도움이 됐으면 좋겠어요.

순수한 SQL의 주요 문장은 다음과 같습니다.

INSERT INTO [simbs] ([En]) OUTPUT INSERTED.[ID] VALUES ('en')

대괄호는 테이블 심브를 정의하고 다음으로 En과 ID 열을 정의합니다.둥근 괄호는 시작할 열의 열거를 정의하고 다음으로 열의 값을 정의합니다(예: 열 하나와 값 하나).아포스트로피는 문자열을 둘러싼다.

제 접근 방식을 설명하겠습니다.

이해하기 어렵겠지만 마지막으로 삽입한 아이디로 큰 그림을 보는 것이 도움이 되었으면 합니다.물론 더 쉬운 대안적 접근법이 있다.하지만 난 내 것을 지켜야 할 이유가 있어.연관된 함수는 포함되지 않으며 이름 및 매개 변수 이름만 포함됩니다.

의료용 인공지능에 사용하는 방법 중앙표(1)에 원하는 문자열이 있는지 확인한다.원하는 문자열이 중앙 테이블 "simbs"에 없거나 중복이 허용되면 원하는 문자열을 중앙 테이블 "simbs"에 추가한다(2).마지막으로 삽입된 ID는 연관된 테이블(3)을 작성하기 위해 사용됩니다.

    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
    }

위의 것을 시도해 봤지만 효과가 없었고, 저는 이 생각을 했습니다.

var ContactID = db.GetLastInsertId();

코드도 적고 넣기도 편하고

이게 도움이 됐으면 좋겠네요.

SQL Server에서 SCOPE_IDENTITY 호출을 사용할 수도 있습니다.

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();
        }
    }
}

Last Inserted ID를 취득하는 방법은 여러 가지가 있지만 가장 쉬운 방법은 다음과 같이 DataSet의 TableAdapter에서 취득하는 것입니다.

<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;

이것이 도움이 되길...

행을 삽입한 후 쿼리 아래 행에서 마지막으로 삽입된 ID를 얻을 수 있습니다.

aspnet_GameProfiles(UserId, GameId) 값(@UserId, @GameId)에 삽입하여 @@IDENTY를 선택합니다.

executeScalar를 사용하는 경우:

cmd.ExecuteScalar();
result_id=cmd.LastInsertedId.ToString();

이 답변은 도움이 될 수 있습니다.또, 데이타베이스에는 「IDENTY」(「SELECT SCOPE_IDENTY()」또는 「@@IDENTY」콜에 필요)로서 지정되어 있는 열이 없는 것 같습니다.또한 "ID" 열은 "binary(16)" 유형이었기 때문에 아래와 같이 출력을 변환해야 했습니다.

string returnId = BitConverter.ToString((byte[])cmd.ExecuteScalar()).Replace("-", ""); 
//   skip the replace if you handle the hyphen otherwise

쿼리에서 SELECT SCOPE_IDENTITY()사용합니다.

그 후:

INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)

이것을 실행하다

int id = (int)command.ExecuteScalar;

그건 작동할 것이다.

aspnet_GameProfiles(UserId, GameId) VALUES(@UserId, @GameId)에 삽입하여 설명 방식으로 테이블을 주문하면 마지막 ID에 액세스할 수 있습니다.

aspnet_GameProfiles ORDER BY UserId DESC에서 TOP 1 UserId를 선택합니다.

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

언급URL : https://stackoverflow.com/questions/5228780/how-to-get-last-inserted-id

반응형