How to use the return table data of one procedure in another procedure? - sql

I had a procedure it will return data from a temporary table.The temporary table structure may varies depends on the input parameter of the procedure.This procedure is a general procedure so i cant modify this one.
My requirement is that i want to use the return temporary table data to do some calculation from another procedure.Is it possible to achieve this one????
requirement is some thing like this
Create Procedure Proc2 ( #Condition int)
As
BEGIN
execute #temp = Proc1 input1,input2
select * from #temp where column1 = #Condition
END
This Proc1 is using in some other procedures also so i cant include the condition inside Proc1.
Am using SQL SERVER 2008 R2
Thejus T V

You need to create a temporary table and use like this
Create Procedure Proc2 ( #Condition int) As
BEGIN
create table #temp(col1 int, col2,....) -- similar to reseultset of proc1
insert into #temp
execute Proc1 input1,input2
select * from #temp where column1 = #Condition
END
If the column names are unknown you can use OPENROWSET
Select
*
from
OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
Integrated Security=SSPI','Execute yourdb..proc1')

If you know the structure being returned by the procedure then you can simply create a temp table and insert the data into that temp table from the stored procedure result set.
Create Table #Temp (Col INT , Col2 INT)
INSERT INTO #Temp
Exec Proc1 input1,input2
But since you have mentioned you don't know the exact structure of the table begin returned from the stored procedure you can use OPENQUERY to manipulate further the result set of a stored procedure something like this....
SELECT *
FROM OPENQUERY(YOURSERVERNAME, 'Proc1 input1,input2')
where column1 = #Condition

Related

Select specific columns from the stored procedure

I have a stored procedure in other database which is maintained by other team. Assume that it is currently returning 3 columns, and my system only needs those 3 columns
but the other team can add few more columns for their own use which is causing my system to fail.
Other database SP
ALTER PROCEDURE FirstSP
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #A (Id INT, Name VARCHAR(200), Amount VARCHAR(100), TestColumn INT)
INSERT INTO #A VALUES
(1,'ABC','23',1), (2,'CDF','35454',2), (3,'hjhj','9809909',3)
SELECT * FROM #A
DROP TABLE #A
END
GO
And below is my query, which was only expecting 3 columns from the source
CREATE TABLE #MyTable (Id INT, Name VARCHAR(200), Amount INT)
INSERT INTO #MyTable
EXEC dbo.FirstSP;
SELECT * FROM #MyTable
DROP TABLE #MyTable
Is there any way I can provide the column list?
This is what I am trying but it seems that I can't use server name as the parameter
DECLARE #ServerName VARCHAR(100) = ##SERVERNAME
SELECT * FROM OPENQUERY(#ServerName,'EXEC dbo.FirstSP')
My whole problem is to just select required columns from the SP. SP can have many columns in future.
Try this:
/*
-----------------------------------------------------------------------
Replace <SERVERNAME>\<INSTANCENAME>], <DATABASENAME> with your names
*/ ------------------------------------------------------------------------
-- First, enable Data Access (One time only)
EXEC sp_serveroption '<SERVERNAME>\<INSTANCENAME>', 'DATA ACCESS', TRUE;
-- Then SELECT just the fields you need
SELECT ID, Name, Amount
FROM OPENQUERY([<SERVERNAME>\<INSTANCENAME>], 'EXEC <DATABASENAME>.dbo.FirstSP')
I would ask the team that develops the stored procedure to create a parameter "Team" or something and slightly change the sp so that it will return the expected columns based on this parameter.
A more cumbersome solution is to use this stored procedure the get the colum names of the (first) result returned by the sp.
sp_describe_first_result_set 'dbo.usp_mySp';
And then use the result to create some dynamic SQL.

Is it possible to call a stored procedure within an INSERT statement?

In a nutshell, here's what I'm trying to do:
CREATE PROCEDURE sp_insertingStuff
#value1
AS
INSERT INTO [my_table] (column1, column2)
VALUES (#value1, execute sp_anotherSP)
GO
What I need to know is: is it possible to execute a stored procedure from within an INSERT statement like that? If there's a better way to do this I'm open to the advice. The reason I need to do something like this is because I need to run some IF statements to get the value for that second column.
execute the second one just above the insert statement inside the first sp
like:
CREATE PROCEDURE sp_insertingStuff
#value1
AS
declare #value2 int
exec #value2 = sp_anotherSP
INSERT [my_table] (
column1,
column2
)
VALUES (
#value1,
#value2
)
GO
You can not execute a sp in the VALUES part. You have to execute and get the return/out value before insert, like this.
CREATE PROCEDURE sp_insertingStuff
#value1
AS
DECLARE #anotherValue INT
execute #anotherValue = sp_anotherSP
INSERT [my_table] (
column1,
column2
)
VALUES (
#value1,
#anotherValue
)
Add OUTPUT parameter in you sp_anotherSP
https://technet.microsoft.com/en-us/library/ms187004(v=sql.105).aspx
and
DECLARE #Val <type>
EXEC sp_anotherSP #Val OUTPUT
... insert using #val
One mentioned solution is to add an OUTPUT parameter. Another is to rewrite your stored procedure as a function, as long as your stored procedure doesn't already UPDATE/INSERT/DELETE any data.
Yes this can be done by making the temp table in the insert sp.
then call the sp that you want to call and store the value in the temp table and then you can use that temp table values in your sp and at last drop that temp table

Insert sql query result inside stored procedure in temp table

I have stored procedure in which i store whole query inside string and then execute that. Now i want to store that execute result into temporary table for further processing.
Something like below :
Exec #Mainsql -- this returns me query result and i need to insert its result to temp table
I tried something like this:
Select * Into #TempTable
From
Exec #MainSQL
But It is lacking in syntax i guess.
So, i need result of mainsql into temptable
Try this:
CREATE TABLE #TempTable AS
Exec #MainSQL
You must create Temp Table first, You have to define all columns which will be returned from procedure, if you need to insert data using Stored Procedure:
CREATE TABLE #TempTable (Col1 INT, Col2 VARCHAR(10))
INSERT INTO #TempTable
EXEC [ProcedureName]
Another option is to use OPENROWSET, if you do not know returned columns :
SELECT * INTO #TempTable
FROM OPENROWSET('SQLNCLI', 'Server=.;Trusted_Connection=yes;', 'EXEC DBName.Schema.ProcedureName')

Execute store procedure like a "table" for SELECT operator (MS SQL SERVER)

Is it possible to execute store procedure
like a "table" for SELECT operator (MS SQL SERVER)?
Something like
SELECT TotalSum FROM exec MyStoreProcedure '2011/11/01', '2011/11/01'
I mean somehow integrate it into the SELECT operator?
Thank you!
Thanks guys!
The solution what I did is based on your answers:
declare #result table (f1 varchar(20),f2 varchar(20), CodProducto int, NomProducto varchar(1000), Costo decimal, Cantidat int, Total decimal)
INSERT INTO #result exec MyStoreProcedure '20111201', '20111201'
select * from #result
I supposed your proc returns several columns and you just want one, right?
small workaround is to add the result of the proc to a table variable and then select from it
create proc proc1 as
select 1 as one, 2 as two
declare #result table (one int, two int)
insert into #result
exec proc1
select one from #result
This would be better as a function rather than a stored procedure.
create function dbo.TestTable
(#var1 bit)
returns table
AS
RETURN
( select *
from INFORMATION_SCHEMA.TABLES
where #var1 = 1
);
select * from
dbo.TestTable(1)
Not directly (or without altering the stored procedure to be a table-valued function).
But you could do this:
INSERT INTO SomeTempTableWithSchemaMatchingTheSproc (...)
EXEC MyStoredProcedure
SELECT * FROM SomeTempTableWithSchemaMatchingTheSproc
SQL Server 2005 onwards, you can also use a table variable.
This works for me:
CREATE VIEW dbo.vw_xxx
AS
select * from openquery(YOURSERVERNAME, 'exec [sp_xxx] '''','''','''','''','''','''' ')

How to query from a stored procedure in SQL Server?

Let say I have a simple Stored Procedure:
ALTER PROCEDURE [dbo].[myProc]
AS
BEGIN
SELECT * FROM myTable
END
How can I do a WHERE statement in Microsoft SQL Server Management Studio to the stored procedure? Something like that:
SELECT * FROM myProc WHERE x = 'a'; -- But that doesn't work...
It sounds like you're trying to make a "dynamic" stored procedure.
Something you might want to do is:
1) Insert the contents of your stored procedure into a temporary table
2) Use dynamic sql to apply a where condition to that temporary table.
Something like:
declare #as_condition varchar(500); --Your condition
create table #a
(
id bigint
)
insert into #a
execute sproc
declare #ls_sql varchar(max);
set #ls_sql = "select * from #a where " + #as_condition;
execute (#ls_sql);
SQL Server allows you to use INSERT INTO to grab a stored procedure's output. For example, to grab all processes with SPID < 10, use:
create table #sp_who (
spid smallint,
ecid smallint,
status nchar(30),
loginame nchar(128),
hostname nchar(128),
blk char(5),
dbname nchar(128),
cmd nchar(16),
request int)
insert into #sp_who execute sp_who
select * from #sp_who where spid < 10
You can't add a WHERE clause to a stored procedure like this.
You should put the clause in the sproc, like this:
ALTER PROCEDURE [dbo].[myProc]
#X VARCHAR(10)
AS
BEGIN
SELECT * FROM myTable WHERE x=#X
END
GO
The syntax for calling a stored procedure is through the use of EXECUTE not SELECT(e.g.):
EXECUTE dbo.myProc 'a'
I think you can't do that.
The command to execute a stored procedure is EXECUTE.
See some more examples of the EXECUTE usage.
I think its better to use a view or a table valued function rather than the suggested approach. Both allow you to pass parameters to the function
If you want the WHERE clause to be something you can "turn off" you can do this, passing in a predetermined value (e.g. -1) if the WHERE limitation is to be bypassed:
ALTER PROCEDURE [dbo].[myProc]
#X VARCHAR(10)
AS
BEGIN
SELECT * FROM myTable WHERE x=#X or #X = -1
END
GO
You must declare a variable in the store procedure which will be necessary to pass to run the stored procedure. Here is an example. Keep this in mind: Before AS you can simply declare any variable by using the # character, but after the AS you must write Declare to declare any variable, e.g., Declare #name nvarchar (50).
ALTER PROCEDURE [dbo].[myProc]
#name varchar (50)
AS
BEGIN
SELECT * FROM myTable
where name= #name
END