Insert data on a table from stored procedure resultset - sql

I have a stored procedure that gets data from different tables. I want a few fields from the result set of the stored procedure to be inserted on another table.
How can I do this? Cursor, another stored procedure or what?

You can insert the result set from a stored procedure into another table, as in this example from this article:
DECLARE #People TABLE
(
ContactID INT,
FirstName NVARCHAR(50),
LastName NVARCHAR(50)
)
INSERT #People (ContactID, FirstName, LastName)
EXEC dbo.GetPeopleByLastName #LastName = 'Alexander'

Related

Return AutoIncremeting ID upon insert

I have a stored procedure that inserts into a table that has two values, id and username. The id field is autoincremeting so my stored procedure looks like:
CREATE PROCEDURE [dbo].[sp_test]
#username varchar(50)
AS
BEGIN
INSERT INTO dbo.testtable(username)
SELECT
#username
FROM
tbl.test2
WHERE
username IS NOT NULL
How can I return the id even when there it is not explicitly stated? I attempted the SCOPE_IDENTITY(); keyword but I was receiving blanks and nulls.
Taking a guess as to what you want I think it would be something more like this.
CREATE PROCEDURE [dbo].[Insert_test]
(
#username varchar(50)
) AS
BEGIN
INSERT INTO dbo.testtable
(
username
)
VALUES
(
#username
)
select SCOPE_IDENTITY()
END
If you're really inserting several rows from a table, you can get the ids this way:
INSERT INTO dbo.testtable(username)
output inserted.id
SELECT username
FROM dbo.test2
where username is not null

Stored Procedure: Keep Query Result (as Table) in variable

I'm from Entity Framework background and I don't do much pure SQL development.
However, when dealing with EF we can do:
var persons = from x in db.Person
where x.Name.Equals("Something")
select x;
or
IQuerable<Person> persons = from x in db.Person
where x.Name.Equals("Something")
select x;
But when dealing with stored procedures, how could this be done exactly, like for example I can capture a variable by declaring DECLARE #Name NVARCHAR(15), but how to get the returned table result?
Create a table variable and insert your data into that:
DECLARE #Person table(
FirstName nvarchar(15),
LastName nvarchar(15)
);
Insert Into #Person(FirstName, LastName)
Select Firstname, LastName
From Person
Where LastName = #LastName; -- where #lastname comes from a sp parameter.
Now do stuff like
Select count(*) from #Person;
simply declare a table variable:
DECLARE #TableVariable TABLE
(
PrimaryKey INT,
Name NVARCHAR(MAX)
)
and insert the results into this table.
One way as answered by #ps2goat. And if you want Stored Procedure output into table then you can do like this :-
DECLARE #Person table
(
Id Int Identity(1,1)
,FirstName nvarchar(15)
,LastName nvarchar(15)
);
Insert Into #Person(FirstName,LastName)
Exec dbo.USP_SomeStoredProcedure <sp's parameters>;
Select Top 1
FirstName
,LastName
From #Person As p
Order By p.Id Asc
Note:- your calling procedure output and table column exactly match should be same
Well I found the right answer myself. I think I have to use cursors and that is the best to do so.

while loop to get two variables to stored procedure

I want to write a stored procedure to loop through the table which has membership id and person id details and pass it as variable to stored procedure.
Any thoughts on how to do it. Any help is highly appreciated.
DECLARE #membership NUMERIC(9)
DECLARE #person_id NUMERIC(9)
DECLARE #id_num INT
WHILE (
set #id_num=id_num+1
SELECT membership_id,person_id FROM [dbo].[reb] WHERE id_num <1160
EXEC p_get_details #membership_id, person_id
You have two options. first one is to pass two parameters to procedure p_get_details , each parameter being a comma separated string containing concatenated values of membership_id and person_id columns.
Other is to pass the whole resultset from SELECT query as a Table Valued Parameter to the procedure.
If you need to call the proc again and again for different table values then u can create a temp table which has all the membership and personids
See If this code works for you:-
DECLARE #membership_id NUMERIC(9)
DECLARE #person_id NUMERIC(9)
if(OBJECT_ID('tempdb..#tempids') is not null)
drop table #tempids
SELECT membership_id,person_id
into #tempids
FROM [dbo].[reb]
WHERE id_num <1160
while exists(select 1 from #tempids)
begin
-- select 1 row which will be called by proc
select top 1 #membership_id=membership_id
#person_id =person_id
from #tempids
EXEC p_get_details #membership_id, #person_id
--delete the ids which have been called by proc
delete from #tempids
where
membership_id=#membership_id
person_id =#person_id
end

Calling stored procedure from another stored procedure SQL Server

I have 3 insert stored procedures each SP inserts data in 2 different tables
Table 1 Table 2
idPerson idProduct
name productName
phoneNumber productdescription
FK-idProduct
SP for table 1 SP for table 2
create procedure test1 create procedure test2
WITH WITH
EXECUTE as caller EXECUTE as caller
AS AS
declare declare
#idPerson int, #idProduct int,
#name varchar(20), #productName varchar(50),
#phone varchar(20) #productoDescription varchar(50)
SET nocount on; SET nocount on;
Begin Begin
insert into table1( insert into table2(
idPerson, idProduct,
name, productName,
phone) productDescription)
values( values(
#idPerson, #idProduct,
#name, #productName,
#phone) #productDescription)
end end
I need to call stored procedure test 2 from stored procedure test 1 and insert the FK-ID in the table 1
Simply call test2 from test1 like:
EXEC test2 #newId, #prod, #desc;
Make sure to get #id using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT #newId = SCOPE_IDENTITY()
You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:
SELECT #NewIdOutputParam = SCOPE_IDENTITY()
Then in test1, retrieve it like so:
DECLARE #NewId INTEGER
EXECUTE test2 #NewId OUTPUT
-- Now use #NewId as needed
First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table
SET IDENTITY_INSERT table2 ON;
before the insert.
So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID
EXEC test2 'productName', 'productDescription'
SET #newID = SCOPE_IDENTIY()
or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

How do I call an stored procedure from another stored procedure in SQL Server?

I have a main stored procedure that insert 3 varchar fields, name, address and phone number and other 3 fields that insert an ID from foreign keys in a table, these 2 foreign key fields also use an insert stored procedure to insert their own data. How do I call those stored procedures from the main SP to insert the varchar fields and the foreign key fields generated when executing them?
Table 1 Table 2 Table 3
id, id2, id3,
name1, name2, name3,
address1, address2, address3,
phoneNumber1, phoneNumber2, phoneNumber3
id2,
id3,
create procedure table1
#id int,
#name1 varchar(30),
#address1 varchar(100),
#phoneNumber1 varchar(30)
as
BEGIN
set nocount on;
Insert into table1
(id,
name,
address,
phoneNumber)
values(
#id,
#name,
#address,
#phoneNumber)
END
------After inserting the data into table 1, I want to call the SP of table 2 and 3---
EXEC SPTable2
From the main procedure:
Insert into table1 (...)
exec yourProcName #param='foo'
You should have each proc return the data set you need and the main proc call each of them and do an INSERT INTO as I showed above.
The table definition of table1 has to match exactly the number of columns and data types of the result sets returned by the other procs.
If you can't guarantee this condition, you are probably better off writing a function that returns a table so that you can do a insert into table1 (....) select col1, col2, etc from fnFoo(#param)