Get last generated ID and add it to another table ASP.NET - c#

How can I get get generated ID from primary key and then add it to another table in ASP.NET via SCOPE_IDENTITY?
For example:
Last generated ID on column NRRENDOR is number 26, I have deleted the rows. Now when I add datas to the database the nexy generated ID on NRRENDOR will be number 27. That number I want it to add to column NRD.

In your INSERT code, assuming it's in a stored procedure, using SCOPE_IDENTITY will get you the last identity that was inserted, which you can either reuse in the stored procedure or return to your app to use in another statement.
Some dummy SQL to demonstrate:
INSERT INTO NRRENDOR(SomeColumn) VALUES(1)
DECLARE #LastID int
// set #LastID to the last id inserted
SELECT #LastID = SCOPE_IDENTITY()
// to use in same procedure
INSERT INTO NRD (SomeColumn) VALUES(#LastID)
// to return it to code - or you could use an output parameter
SELECT #LastID

What has this got to do with ASP.NET? SQL would suffice.
INSERT INTO [Table2]( NRD)
SELECT MAX(NRRENDOR)
FROM Table1
' WITH (ROWLOCK, XLOCK, HOLDLOCK)
The correct way to do it will be to use #SCOPE_IDENTITY after you perform insertion as Tanner suggested. It will be worth noting that there is another way to get the current identity, ie, IDENT_CURRENT. You can use it like this
SELECT IDENT_CURRENT('Table1') + 1 as Current_Identity
Please note this too
Be cautious about using IDENT_CURRENT to predict the next generated
identity value. The actual generated value may be different from
IDENT_CURRENT plus IDENT_INCR because of insertions performed by other
sessions.
This comment from marc_s sums it all. How to get the next identity value from SQL Server

Related

How can i set the id from one table to another table

I have a question, let's say I have two tables I am doing an insert operation to the first table with the stored procedure, but how do I insert the auto incrementing ID in the first table in the other table? 🤔🤔
Would be good if you provided one example of what you are trying to achieve.
To get the inserted Id by the store procedure, you could use SCOPE_IDENTITY.
SCOPE_IDENTITY(): returns the last identity value generated in the current scope.
For instance:
INSERT INTO.... VALUES(); SELECT SCOPE_IDENTITY();
This query will insert into a the given table and will return the id inserted.
You can also use Select ##IDENTITY, this will return the last id inserted regardless the scope.
INSERT INTO.... VALUES(); SELECT ##IDENTITY;

Oracle: Fastest way to UPSERT and return the last affected Row ID in oracle for large data sets

This table schema in question is here: Oracle SQL: Selecting a single row with the latest date between multiple columns
I'm working with a table that has over 5 million entries. What is the fastest and most accurate way to upsert to this table AND return the last upserted row id using a stored procedure?
Most of what I've read recommends using the merge statement for upserts. However, merge doesn't support returning into.
In our table, we have the CREATE_DATE, CREATE_USER, UPDATE_DATE, and UPDATE_USER fields that are updated as expected. My thought was to create a stored procedure that returned the id of the row that has the latest date between those two columns and where the respective user data was equal to the current user data. This is what the people who answered the referring question helped me with (thanks!).
However, I'm concerned about the combined execution time vs other methods, as well as the huge gaps created in sequences due to merging. Calling a separate statement simply to get the id also seems a bit inefficient. However, almost everything I've read says that merge is much faster than the pre-merge upsert statements.
Note that these are being called through a c#/asp web application. Any help is appreciated :)
edit
Below is an example of the stored procedure I'm using for the Upsert. Note that the CREATE_DATE and UPDATE_DATE columns are updated with triggers.
create or replace
PROCEDURE P_SAVE_EXAMPLE_TABLE_ROW
(
pID IN OUT EXAMPLE_TABLE.ID%type,
--Other row params here
pUSER IN EXAMPLE_TABLE.CREATE_USER%type,
pPLSQLErrorNumber OUT NUMBER,
pPLSQLErrorMessage OUT VARCHAR2
)
AS
BEGIN
MERGE INTO USERS_WORKGROUPS_XREF USING dual ON (ID=pID)
WHEN NOT MATCHED THEN
INSERT (--OTHER COLS--, CREATE_USER) VALUES (--OTHER COLS--, pUSER)
WHEN MATCHED THEN
UPDATE SET
--OTHER COLS--
UPDATE_USER=pUSER
WHERE ID=pID;
EXCEPTION
WHEN OTHERS THEN
pID := 0;
pPLSQLErrorNumber := SQLCODE;
pPLSQLErrorMessage := SUBSTR(SQLERRM, 1, 256);
RETURN;
-- STATEMENT TO RETURN LAST AFFECTED ID INTO pID GOES HERE
END;
If you're trying to return the maximum value of a sequence-generated PK on the table then I'd just run a "Select max(id) .." directly afterwards. If other sessions are also modifying the table then maybe reading the currval of the sequence would be better.

Making a substring plus data from sql database column

I am trying to create, lets say a user ID. I have a sql server database and i have a user webpage developed in asp.net. On my user page, a user fill out the information in the text boxes(First Name, Last Name, Middle Initial and so on) and when a user clicks a submit button, the entered information is added to a database. I have an auto increment column in the database, so when the information is added to the database the row has a auto increment number, for example 1. Each time the new row is added the auto increment number rises on one.
I want to create an unique UserID. It should contain the first 4 letters of a Last Name, which user fills out on a user web page and the auto increment number from the database. I have a code to retrieve the first 4 letters of the last name ( string FirstFour = txtNewUserLN.Text.Substring(0, 4);) but i need to add auto increment number from the database to that string.
Could anyone help me with it?
Create an sql user defined function in sql database
for create an function
use
CREATE FUNCTION ucernamehandle(#Lastname)
RETURNS nchar(50)
AS
BEGIN
DECLARE #idfromauo int;
DECLARE #newusernem nchar(50);
SET #idfromauo =IDENT_CURRENT('yourtablename');
return #Lastname+#idfromauo;
END
and then use it in inset statement like
INSERT INTO yourtablename (LastName) VALUES (ucernamehandle(#Lastname))
then exactly you will get witch you want
welcome for your thank's
best of luck
My guess is you are going to have to do an insert and then an update. Something to watch out for - if you use anything that checks for the last or just inserted identity value, make sure you put it in a transaction. If you don't you could have other processes adding a record before you update.
So try something like this:
insert into UserList(LastName, FirstName, ...) values (#LastName, #FirstName)
declare #UserID varchar(500)
set #UserID = left(#LastName, 4) + convert(varchar(10), SCOPE_IDENTITY())
update UserList set UserID = #UserID where RowID = Scope_identity()

Is there any way to use SCOPE_IDENTITY if using a multiple insert statement?

I will import many data rows from a csv file into a SQL Server database (through a web application). I need the auto generated id value back for the client.
If I do this in a loop, the performance is very bad (but I can use SCOPE_IDENTITY() without any problems).
A more performant solution would be a way like this:
INSERT INTO [MyTable]
VALUES ('1'), ('2'), ('3')
SELECT SCOPE_IDENTITY()
Is there any way to get all generated IDs and not only the last generated id?
No, SCOPE_IDENTITY() only gives you the one, latest inserted IDENTITY value. But you could check out the OUTPUT clause of SQL Server ....
DECLARE #IdentityTable TABLE (SomeKeyValue INT, NewIdentity INT)
INSERT INTO [MyTable]
OUTPUT Inserted.Keyvalue, Inserted.ID INTO #IdentityTable(SomeKeyValue, NewIdentity)
VALUES ('1'), ('2'), ('3')
Once you've run your INSERT statement, the table variable will hold "some key value" (for you, to identify the row) and the newly inserted ID values for each row inserted. Now go crazy with this! :-)

How to save a new record when the id key is auto incremented

I have created a database in sql server 2008 and a table with auto increment id field
Also I develop a project in c#.net 2008
The problem occurs on click "save data" after of "add new" from BindingNavigator
for example I click "add new", fill all fields except id text (blanked id) and then click 'save data' then occurs the errors
The runtime exception is "notNullAllowedException: the column 'id' not allowed null.
But it is not required from the user to fill this field but has to returned from database after the save
I also set the properties of the id: (both c# project and sql server)
AutoIncrement = True
AutoIncrementStep = -1 (also I tested 1)
AutoIncrementSeed = -1 (also I tested 1)
No results.
How I could handled that?
Thanks
Don't include the identity column in your Insert statement.
If your statement is
INSERT INTO MyTable (ID, SomeField, SomeOtherField) VALUES (null, 'SomeValue', 'AnotherValue')
simply change it to
INSERT INTO MyTable ( SomeField, SomeOtherField) VALUES ( 'SomeValue', 'AnotherValue')
It sounds like you have two problems.
First, you're always inserting - what logic do you use to decide whether 'save' should be an insert or an update? I think this is the case becuase of the errors you're getting: "Cannot insert explicit..."
Second, you need to get the ID that SQL assinged on your insert so you can write it to your ID field for the next save=update. There are a couple of ways to do this, the way I prefer is to use a stored procedure to do the insert and pass an OUTPUT parameter that gets SCOPE_IDENTITY(). Something like this:
CREATE PROC xyz
(
#data...
#NEWID INT OUTPUT
)
AS
... do your INSERT ...
SET #NewID = SCOPE_IDENTITY()
)
double-check my syntax - not sure what version of SQL you're using

Categories