I want to select back the data I just inserted into the database. I know OUTPUT can be used and we can call INSERTED.[ColumnName] to grab the values that were inserted. Can these values be set to a variable of some kind or given an alias? I do not want to use a TEMP table because I wish to use variables if possible.
It would be nice for the solution to work when the PK is or is not an identity column.
EDIT: Contacts.PhoneNumberID is a foreign key to PhoneNumber.ID I want to do both insert statements back to back and I need the ID from PhoneNumber to use for the Contacts.PhoneNumberID
EDIT: [PhoneNumber].[ID] has a default specified in the database, that is how the ID is being set
Here is what I am looking for:
INSERT INTO [PhoneNumber] (Number)
OUTPUT INSERTED.ID, INSERTED.Number
VALUES ('555-555-5555')
INSERT INTO [Contacts] (Name,PhoneNumberID)
VALUES ('SomeName', {ID From previous insert})
Can we some how alias the insert statement to say:
INSERT INTO [PhoneNumber] (Number)
OUTPUT INSERTED.ID, INSERTED.Number
VALUES ('555-555-5555') as A
I know we cannot actually Alias an insert statement as done above, I am looking for the proper way to do this.
Then you could do this:
INSERT INTO [Contacts] (Name,PhoneNumberID)
VALUES ('SomeName', A.ID)
I am going for a final result of something similar to this:
INSERT INTO [PhoneNumber] (Number)
OUTPUT INSERTED.ID, INSERTED.Number
VALUES ('555-555-5555') as A
INSERT INTO [Contacts] (Name,PhoneNumberID)
VALUES ('SomeName', A.ID)
Reason I am trying to do this:
I wish to put both insert statements in a transaction block, if one of them fails then I can rollback and not commit anything.