• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 345
  • Last Modified:

Returning identity from a function

I'm using this really nice function borrowed from stackoverflow.com/questions/10914576/tsql-split-string, and when I utilize it, I'm able to return Orders and UserIDs below.

OrderID      UserID
1              22
1              23
1              24

However, I'd like to also return the identity to each row. How can this be done using the function?

  • 2
1 Solution
Firstly, define "identity". Remember that SQL has no real concept of sequentiality, so there should be no "first", "second", etc.

Go back to your StackOverflow page and look at the first example. You can add another field - ident, say - to the table declaration, making it an int and an identity, and it will give you a new number value every time you add a record.

Remember that the order in which you retrieve the elements may not be in your definition of order by "identity"!


barnescoAuthor Commented:
Mike, I see what you mean. You answered the question exactly as I asked, but I should have rephrased the question another way--my bad. What I need is to find the @@identity of the values from the table I'm inserting into, but I'll ask that in another question. Thanks for your help.
You can do that, np! Look up the OUTPUT clause for the INSERT statement:
create table dbo.Test (Id bigint IDENTITY(1,1) NOT NULL,
                                        Name varchar(50) NULL                        )
declare @intInsertedId BIGINT

insert into Test
    output @intInsertedId = inserted.Id
    select 'DcpKing'

select @intInsertedId;

Open in new window

SQL Server maintains a virtual table called Inserted when you do an insert. Likewise for update, merge, and delete statements. This lets you insert a number of rows (so long as they're all in the same statement) and then pull back the assigned ID of each!


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now