Insert and select in different SQL queries

I have a server and many clients, my application is on clients and the database on the server, I have one table

Table -->  Id --> int Auto-increment,   
Name --> nvarchar(50),

So, whenever I insert a new line from the client with the request

Insert into Table Name Values('NameValue')

Inserts a row, and sql auto generates an Id field. So, to get my id, I use the following query

Select max(Id) as maxId from Table

but both requests are in different connections

It works well when only one client works, but when several clients work, many insert requests are requested by clients before I can request a getMaxId request.

+3
source share
8 answers

You can use the following:

SELECT SCOPE_IDENTITY()

The identifier with the last entry is selected here.

+2

:

DECLARE @a TABLE (
    Id int IDENTITY (1, 1),
    b VARCHAR(1000)
)

DECLARE @b TABLE (
    Id INT
)

INSERT @a (b)
OUTPUT INSERTED.Id INTO @b
SELECT NAME 
FROM sys.objects


SELECT * FROM @a
SELECT * FROM @b

:

SELECT IDENT_CURRENT('TABLE_NAME')

SELECT SCOPE_IDENTITY()
+2

- , .

.

SELECT SCOPE_IDENTITY()

A, , B, A, @@IDENTITY B

+2

:

select @@identity

select max(id)...

.

+1

, PHP

$id = mysql_insert_id();

#

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

+1

Max (id).

SELECT SCOPE_IDENTITY()
0

Make a function in sql where you add a row and get the SELECT SCOPE_IDENTITY () identifier. While you call the function, you will get an identifier that is exactly added.

0
source

try this hope, it will help you.

  declare @table1 table(id int identity,name varchar(50))
    insert into @table1 (name) output inserted.id  values('abc') 
    insert into @table1 (name) output inserted.id values('xyz')
    insert into @table1 (name) output inserted.id values('pqr')

See here for more details.

0
source

All Articles