What can I do instead execute stored procedure in sql server function - sql

In a select statement I am calling a function which I should show result of it in the result table of select statement. In this function, I need to recreate (it is just checking actually if it is necessary to be recreated or not then it will recreate if necessary) a table which the function uses and I know I can not do that in a function so I created a stored procedure to recreate the table.
I can not exec stored procedure before the select statement because I need to do that in every row. Because the content of the table may need to be changed according to parameters of it every time.
But I know that I also can not exec a stored procedure within a function because of this error Only functions and some extended stored procedures can be executed from within a function. So in final situation, I need to exec stored procedure in a function in order to recreate the table or I need to create a non-temporary table in a function. I could not find any solution for this. Is there any solution to do that in a different way?
I am trying to explain what am I trying to do in details. The table that I mentioned above, stores a list of start times and end times of some workers. In the function I am using this time informations and doing something with it.
But In my select statement I am sending a time parameter to the funciton and this time can be old, for example a month ago. And start and end hours of workers can be different at a month ago. So in this situation according to time parameter of the function I may need to recreate the table. But I can not do that in a function so I did it in a stored procedure but I can not exec this stored procedure in a function as well. And I also can not create a table in the function.

Related

Return table from stored procedure / function after doing merge function SQL Server

I have a stored procedure that takes one table, and doing merge to another table. I want to get a table of logs with the data of what happened to each row, without inserting the data to a table.
I understand a stored procedure cannot return a table, and therefore I thought about using a function, but as of my understanding a function can not make transformations on tables.
Is combining a stored procedure with a function the solution? Or is there any thing else that I am not aware of?
A stored procedure can certainly return a result set, which the client can consume directly just like a regular SELECT statement.
That said, there are a range of options, none of which are perfect. Each suits a different scenario, and are described at length by Erland Sommarskog in How to Share Data between Stored Procedures:
Table-valued Functions
Inline Functions
Multi-statement Functions
Using a Table
Sharing a Temp Table
Process-keyed Table
INSERT-EXEC
Using SQLCLR
OPENQUERY
XML
Cursor Variables
For example, you may not wish to use a permanent table, but a temporary table created by the client and populated by the stored procedure can work well, if directly consuming the results of a SELECT inside the procedure is not suitable.

How to suppress record sets returned by SELECT statements in a Stored Procedure

I'm writing a stored procedure which checks for the existence of various tables in various databases, as well as the permissions that the user executing the stored procedure has on those tables. The stored procedure itself resides within a user database (i.e. it's not in the Master db).
To perform my checks, my stored procedure contains lots of SELECT statements. Each of those obviously returns a record set. What I would like is to somehow suppress these record sets so that they are not returned by the stored procedure, and instead return my own, single record set which is just a collection of messages relating to each check the stored procedure performs.
I think the obvious answer is to use a table-valued function instead, but I've not been able to recreate my tests successfully in a Function as they appear in the stored procedure. For starters, I'm having to use temporary tables (not possible in a function) and dynamic SQL (not very compatible with table parameters).
I think I've basically got two choices:
Rewrite my stored procedure as a function and figure out how to do the checks a different way.
Continue using my stored procedure and use an OUTPUT parameter to return my result messages, probably as a delimited string, and in the associated ASP.NET application just ignore all the record sets the stored procedure returns .
Neither of these solutions is very satisfactory. Before I spend any more time pursuing either one, is there a way to discard the record sets produced by the SELECT statements in a stored procedure and explicitly define what record I want it to return?
Hmm, I only can speculate here...
Are you using something like
SELECT ...;
IF ##rowcount > 0
BEGIN
...
END;
?
Then you can rewrite it using something like
IF EXISTS (SELECT ...)
BEGIN
...
END;
or
DECLARE #variable integer;
SELECT #variable = count(*) ...;
IF #variable > 0
BEGIN
...
END;
In general point the results of your queries to a target (variable, table, expression, ...), then they don't get outputted.
And then just execute the query for your desired result in the end.
In my opinion, here is almost no reason to have stored procedures produce record sets. That is what stored functions are for. On occasion, it is needed, because of the use of dynamic SQL or other stored procedures, but not as a general practice. Much, much too often, I see stored procedures being used where stored functions or views are more appropriate.
What should you do? Even SELECT statement in the stored procedure should be one of the following:
Setting (local) variables.
Saving the results in a temporary table or table variable.
The logic for the stored procedure should be working on the local variables. The results should be returned using OUTPUT parameters.
If you need to return rows in a tabular format, you can do that using tables explicitly (such as a global temporary table or real table). Or, you can have one SELECT at the end that does return a single result set. However, if you need this and can phrase the stored procedure as a function, that is better in my opinion.

Manipulating data from a stored procedure by saving data into a table

Problem: I have a stored procedure in SQL Server 2012 and I want to put constraints to the output so I only get relevant information.
I am using Execute. The way I see it I have two options:
save the result of the execution into a table, so I can use it for different purposes
put constraints to the variables in Execute so I only get the results I want
The first method is discussed here:
Insert results of a stored procedure into a temporary table .
My code is (due to company information I can't share the whole thing):
create table #mtable ( .... )
Insert into #mtable
Execute [myProcedure]
The error:
An INSERT EXEC statement cannot be nested.
I assume the error is because of the code in the stored procedure. How can I fix that problem without looking into the code for the stored procedure. Is there another way where I can save the content in a table?
My problem can also be solved by proposal #2. Is it possible for me to manipulate the output from the stored procedure with something like:
Execute [myProcedure] where variable1 > 100

SQL: Using Stored Procedure within a Stored Procedure

I have a few stored procedures that return the same set of data (same columns) to a user. The stored procedure called depends on certain conditions. These stored procedures are fairly intensive and are being run by every user of the system. I would like to create stored procedure that calls each of these procedures and stores the data on a separate table. I will then run this new stored procedure every 5 minutes or so and let the users pull from the new table.
T_OutboundCallList is a permanent table with the same columns as returned by the two stored procedures.
I would like something like the following but when I try to run this it just runs continuously and I have to stop the procedure.
BEGIN
TRUNCATE TABLE T_OutboundCallList
INSERT T_OutboundCallList EXECUTE p_LeadVendor_GetCallsForCallList
INSERT T_OutboundCallList EXECUTE p_CallLog_GetAbandonedCallsCallList
END
Each of the procedures (*CallList) return a list of calls to be made and I do want them entered into the new table in this order (LeadVendor calls before AbandonedCalls). I also need to clear the table before adding the calls as there may be new calls that need to be higher in the list.
Is there some problem with this procedure that I am not seeing?
Thanks,
Brian
Without seeing the code in your *CallList procs it is hard to say what issue you are having. You should have the insert commands inside of your nested procedure. You can use the results of a procedure to insert data, but not like you are above. It is using OPENROWSET, and I think you will be better off the way I suggested.

Access to Result sets from within Stored procedures Transact-SQL SQL Server

I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?
CREATE PROCEDURE getOrder (#orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = #orderId
select item, number_of_items, cost from order_line where order_id = #orderId
END
I need to be able to iterate through both result sets individually.
EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.
The result sets returned by the procedures are not the same data types or number of columns.
The short answer is: you can't do it.
From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.
To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax:
INSERT INTO #Table (...columns...)
EXEC MySproc ...parameters...
You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.
I was easily able to do this by creating a SQL2005 CLR stored procedure which contained an internal dataset.
You see, a new SqlDataAdapter will .Fill a multiple-result-set sproc into a multiple-table dataset by default. The data in these tables can in turn be inserted into #Temp tables in the calling sproc you wish to write. dataset.ReadXmlSchema will show you the schema of each result set.
Step 1: Begin writing the sproc which will read the data from the multi-result-set sproc
a. Create a separate table for each result set according to the schema.
CREATE PROCEDURE [dbo].[usp_SF_Read] AS
SET NOCOUNT ON;
CREATE TABLE #Table01 (Document_ID VARCHAR(100)
, Document_status_definition_uid INT
, Document_status_Code VARCHAR(100)
, Attachment_count INT
, PRIMARY KEY (Document_ID));
b. At this point you may need to declare a cursor to repetitively call the CLR sproc you will create here:
Step 2: Make the CLR Sproc
Partial Public Class StoredProcedures
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub usp_SF_ReadSFIntoTables()
End Sub
End Class
a. Connect using New SqlConnection("context connection=true").
b. Set up a command object (cmd) to contain the multiple-result-set sproc.
c. Get all the data using the following:
Dim dataset As DataSet = New DataSet
With New SqlDataAdapter(cmd)
.Fill(dataset) ' get all the data.
End With
'you can use dataset.ReadXmlSchema at this point...
d. Iterate over each table and insert every row into the appropriate temp table (which you created in step one above).
Final note:
In my experience, you may wish to enforce some relationships between your tables so you know which batch each record came from.
That's all there was to it!
~ Shaun, Near Seattle
There is a kludge that you can do as well. Add an optional parameter N int to your sproc. Default the value of N to -1. If the value of N is -1, then do every one of your selects. Otherwise, do the Nth select and only the Nth select.
For example,
if (N = -1 or N = 0)
select ...
if (N = -1 or N = 1)
select ...
The callers of your sproc who do not specify N will get a result set with more than one tables. If you need to extract one or more of these tables from another sproc, simply call your sproc specifying a value for N. You'll have to call the sproc one time for each table you wish to extract. Inefficient if you need more than one table from the result set, but it does work in pure TSQL.
Note that there's an extra, undocumented limitation to the INSERT INTO ... EXEC statement: it cannot be nested. That is, the stored proc that the EXEC calls (or any that it calls in turn) cannot itself do an INSERT INTO ... EXEC. It appears that there's a single scratchpad per process that accumulates the result, and if they're nested you'll get an error when the caller opens this up, and then the callee tries to open it again.
Matthieu, you'd need to maintain separate temp tables for each "type" of result. Also, if you're executing the same one multiple times, you might need to add an extra column to that result to indicate which call it resulted from.
Sadly it is impossible to do this. The problem is, of course, that there is no SQL Syntax to allow it. It happens 'beneath the hood' of course, but you can't get at these other results in TSQL, only from the application via ODBC or whatever.
There is a way round it, as with most things. The trick is to use ole automation in TSQL to create an ADODB object which opens each resultset in turn and write the results to the tables you nominate (or do whatever you want with the resultsets). you can also do it in DMO if you enjoy pain.
There are two ways to do this easily. Either stick the results in a temp table and then reference the temp table from your sproc. The other alternative is to put the results into an XML variable that is used as an OUTPUT variable.
There are, however, pros and cons to both of these options. With a temporary table, you'll need to add code to the script that creates the calling procedure to create the temporary table before modifying the procedure. Also, you should clean up the temp table at the end of the procedure.
With the XML, it can be memory intensive and slow.
You could select them into temp tables or write table valued functions to return result sets. Are asking how to iterate through the result sets?