I have a stored procedure with a SELECT statement that outputs one row. It is something like this:
CREATE PROCEDURE [dbo].[CreateCustomer]
...
INSERT INTO Customers values(, , , ,)
SELECT CustomerID, FirstName, LastNam.....
INSERT Roles values(, , , .....
This selects the newly stored values back from the Customers table. The second insert uses the new CustomerID to insert a new row to the Roles table.
Is there a way to just get the customerID from the above select statement without querying again for the CustomerID?
I have tried to declare a variable and do it like this:
SELECT takenCustomerID = CustomerID, FirstName, LastNam....(rest of query statement)
But I have to declare all the variables and do it this way:
SELECT takenCustomerID, takenFirstName, takenLastNa... = CustomerID, FirstName, LastNam... (rest of query statement)
But, I think this is bad because it wastes lot of memory on the server side.
So, is there an easy way of getting individual values right away without declaring all the variables in the select statement, such as an inbuilt TEMP-like variable where I can call TEMP(“customerID”) and get that value?
Also, Can there be more than one SELECT statement in a stored procedure? How can we get the select values from the select statement we want?
I am asking more out of curiosity because I already know a way to get the value. I just want to know if there is a more elegant way.
Accessing Inserted Values
It is simple. Use the
OUTPUTclause to return the values you just created.Then you can do this:
If you have no further use for the values from the inserted Customer row, you could even do away with the table variable and just OUTPUT directly into the Roles table, assuming that all the values that go into that come from variables.
The
OUTPUTclause gives access to the inserted values using the special meta-tableInserted. However, you can use variables and expressions with constants as well.The good thing about using this method is that you can handle many inserted rows at once. If you are inserting only one row, you need only the
CustomerIDafterward, and you need to use it more than once, then instead do it this way:By creating the GUID in advance, you don’t need to get it back out of the table. By the way,
newsequentialid()is probably superior tonewid()if it is the clustered index (which is probably true), because you will avoid the page splits thatnewidwould cause.Returning Multiple Result Sets
This is always possible. Whatever means you are using to query will have a method that advances your data access object to the next recordset. If you’re using a
DataReaderthen look into theNextResultmethod. In Classic ADO, recordsets have aNextRecordsetmethod.