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

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] '''','''','''','''','''','''' ')

Related

How to get a dataset returned from a stored procedure in temp table

I have a stored procedure which returns a dataset
Let's say its name is spx and it returns
I'd name
1. Abc
2. Def
I want to get it's result in a temp table in another stored procedure dynamically like if in future I change the dataset in my above so it will reflect here
Like this
exec spx
It will execute the SP and I want it's result set in a table
Any help would be much appreciated. Thanks.
If you want to define the temporary table you can use standard SQL
CREATE TABLE #tmpTable
(
ID INT,
Name nvarchar(50)
)
INSERT INTO #TempTable
EXEC spTest
Select * FROM #TempTable
If you don't want to define the table you can use OPENROWSET
SELECT * INTO #TempTable FROM OPENROWSET('SQLNCLI', 'Server=(local);Trusted_Connection=yes;', 'EXEC spTest')
Select * FROM #TempTable
You can try this:
SELECT * INTO [temp-table] FROM OPENQUERY("server-name", 'EXEC spx');

SQL Server : how to get specific column from stored procedure without modifying it

Here is the sample stored procedure
DECLARE #ReturnTable TABLE (DateTime DATETIME,
WrongUSSD VARCHAR(30),
AllMSISDN INT,
UniqueMSISDN INT,
SubscriptionActivated INT)
SELECT *
FROM #ReturnTable
Modification in stored procedure is not allowed, I just need specific column form this procedure by select statement.
I have tried this
select WrongUSSD
FROM openrowset('MSDASQL', 'Driver={SQL SERVER}; Server=server_name;UID=user; PWD=pass;Trusted_Connection=yes;', 'EXEC [DatabaseName].[dbo].[ProcedureName] "2016-01-01","2016-04-01"') as a
This method doesn't work if the is link server exists in stored procedure
Is there any other method?? Please help
Using temp table:
INSERT INTO #TempTable
EXEC [dbo].[ProcedureName]
SELECT WrongUSSD
FROM #TempTable

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

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

How do I combine result sets from two stored procedure calls?

I have a following stored procedure
CREATE PROCEDURE [dbo].[MyStored]
#state int
AS
SELECT blahblahblah WHERE StoredState=#state LotsOfJoinsFollow;
RETURN 0
and I'd like to call that stored procedure with #state being 0 and 1 and have the result sets returned by both calls combined with UNION semantics so that I have a new resultset that has rows from both the first call and the second call.
Something like (imaginary SQL):
(EXEC MyStored 0) UNION (EXEC MyStored 1);
How do I achieve that?
This may be oversimplifying the problem, but if you have control over the sp, just use in rather than =:
CREATE PROCEDURE [dbo].[MyStored]
AS
SELECT blahblahblah WHERE StoredState IN (0,1) LotsOfJoinsFollow;
RETURN 0
If this is not an option, just push the results of both sproc calls into a temp table:
/*Create a table with the same columns that the sproc returns*/
CREATE TABLE #tempblahblah(blahblahblah NVARCHAR(50))
INSERT #tempblahblah ( blahblahblah )
EXEC MyStored 0
INSERT #tempblahblah ( blahblahblah )
EXEC MyStored 1
SELECT * FROM #tempblahblah
create table #table (
.....
)
insert into #table exec MyStored 0
insert into #table exec MyStored 1
select * from #table
drop table #table
Alternatively to a series of statements like these:
INSERT INTO #YourTempTable
EXEC MyStored 0;
INSERT INTO #YourTempTable
EXEC MyStored 1;
you could use one INSERT ... EXEC statement like below:
INSERT INTO #YourTempTable
EXEC ('
EXEC MyStored 0;
EXEC MyStored 1;
');
The results of the two calls to MyStored would be UNIONed (or, rather, UNION ALLed), just like with the former method.
A long way would be to create a wrapper that does this - a function that takes a list of states and adds them to a final table that would be returned.
You could also have whatever technology is calling this procedure do the concatination of records (i.e. having .NET append the result set of each state you are looking into)
If you're fine with passing in a list of states to your 'state' param, you could create a dynamic sql query
CREATE PROCEDURE [dbo].[MyStored]
#state nvarchar(150)
AS
-- #state needs to be pre-formatted in a list for an in-clause
-- i.e. 1,2,10 (if it was a string list, you'd need to do use double single quotes around the items - ''1'',''2'',''10''
DECLARE #SQL nVarChar(5000) = '
SELECT blahblahblah
FROM LotsOfJoins
WHERE StoredState in (' + #state + ')'
exec sp_executeSql #sql
This works great for simple procedures; although, it can get take longer to maintain if changes are needed down the road.
.
Here is a CodeProject Article and a MS SQL Tips Article that does a better job going into details
.
EDIT: The param #state will need to be a nVarChar since your passing in a comma delimited list of int values
If the stored procedure you are calling has a temp table with the same name as one in the calling procedure you will get this error.
e.g. sp1 has temp table #results
sp2 create table #results(fields)
then trying to insert into #results in sp2 the result of calling sp1 would fail with this error. change temp table in sp2 to #result and try again and you should see this now works.

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