Convert Query to Stored Procedure - sql

In db2, can someone show me how to convert a query into a stored procedure, so that when the stored procedure is called it simply returns the same result set as the query would return.
For example, let say I have query like this:
select * from tablename
How would you turn this into a stored procedure that returns the same record set as is returned by just simply running the query directly?

Just create a procedure
Format is as follows
CREATE PROCEDURE <<SPmyProcedure>>
AS
BEGIN
<---procedure definition here--->
select * from tablename
END
Then you can just call the procedure name and it will perform your query.
via
exec SPmyProcedure

Why you dont use table valued function like this?
ALTER FUNCTION [db].[fn_tablename]
(
)
RETURNS TABLE
AS
RETURN
(
SELECT * from [db].tablename
)

Related

Storing results of a stored procedure in a Google Big Query table

Here is a link to the question I asked earlier. The accepted answer works perfectly.
But this stored procedure processes 2 statements and after running this procedure I have to click on View Results of the second statement to see the result in Google Big Query. Is there a way to save the results in some table automatically using the 'Query Settings' in Google Big Query and specifying the name of the table I want to store the results in?
You cannot set a destination table for a script (or for call a procedure), instead, you can convert your SELECT statement into CREATE TABLE ... AS SELECT, for example:
SELECT 1 x;
=>
CREATE TABLE myDataset.myTable
AS SELECT 1 x;
You can define a string parameter for your procedure. Then use this parameter in the dynamic query to write the results to the table.
CREATE OR REPLACE PROCEDURE `my_dataset.my_procedure`(destination_table STRING)
BEGIN
CREATE TEMP TABLE tmp AS SELECT 1 x;
EXECUTE IMMEDIATE (
FORMAT("CREATE OR REPLACE TABLE `%s` AS SELECT * FROM tmp", destination_table));
END
Now you can provide a table name and call this procedure to write the results to the table.
CALL `my_dataset.my_procedure`("my_dataset.my_table");
SELECT * FROM `my_dataset.my_table`

Execute a stored procedure from within another stored procedure's SELECT statement?

I would like to execute a stored procedure X from within the SELECT statement of stored procedure Y, so that X's value can be returned as part of Y's data.
I am trying the following syntax, but it's apparently not valid.
SELECT name, type, (EXEC X #type=type)
FROM table
As I hope you can see above, I need to pass the current row's type value to procedure X to get the proper return value.
Disclaimer: I probably just don't know what I'm doing.
The approach what you have tried is invalid. Instead of the X as the stored procedure convert it as user-defined function. like the below
Create function dbo.fnGetTypeDetail
(
#type varchar(50)
)
returns varchar(100)
As
Begin
return --do your operation;
End
And replace your query as:
SELECT name, type, dbo.fnGetTypeDetail(type) AS TypeDetail
FROM table
For sample, I created a scalar function. Based on your requirement you can create inline table valued function as per the example
You can't EXEC a stored proc inside a SELECT statement.
What you can do is INSERT..EXEC a stored proc into a temp table, and then run a SELECT statement that queries that temp table, while joining to other tables if desired.
Psuedo-example:
INSERT INTO #Tmp (Column1) EXEC X;
SELECT Name, Type, (SELECT Column1 FROM #tmp)
FROM MyTable

Can I search stored procedure results?

Let's say I have a stored procedure which returns a large set of data. Can I write another query to filter the result of stored procedure?
For example:
select * from
EXEC xp_readerrorlog
where LogDate = '2011-02-15'
You would need to first insert the results of the stored procedure on a table, and then query those results.
create table #result (LogDate datetime, ProcessInfo varchar(20),Text text)
INSERT INTO #Result
EXEC xp_readerrorlog
SELECT *
FROM #Result
WHERE datepart(yy,LogDate) = '2012'
You can't make it part of a query, BUT you could insert the resulting data into a temp table or table variable and then use that for your query.
Does returning the error log for just an entire day make the result any more useful? I think it will still be full of useless entries. If you're looking for specific events, why not use one of the filter parameters for xp_readerrorlog? The following wil return all rows in the current log that contain the string 'fail':
EXEC xp_readerrorlog 0, 1, 'fail';
You can copy output from sp to temporaty table.
insert into #temp
EXEC xp_readerrorlog
and then use where clause with the temp table
or you can make a Table-valued Function

Insert SQL stored procedure values into another stored procedure

I have a large stored procedure that returns a record for a person, there are four fields that I need to return very specific values for. I have another stored procedure that performs this specific action.
The small stored procedure is as follows:
SELECT TOP 1
wea.field,
wea.degree,
wea.degreeyear,
wpp.ProgramCategory
FROM dbo.webeventaffiliation wea
LEFT JOIN dbo.WebProgramParticipants wpp
ON
wea.userid = wpp.UserID AND
wea.eventid = wpp.eventid
INNER JOIN dbo.WebProgramCategoryDescriptions wpcd
ON
wpcd.ProgramCategory = wpp.ProgramCategory
WHERE wea.UserID = #UserID
ORDER BY wea.datelastmodified DESC
LARGE STORED PROCEDURE SAMPLE RETURN DATA:
Name: XXXXX
Address: XXXXX
Field: [small stored procedure value]
Degree: [small stored procedure value]
DegreeYear: [small stored procedure value]
ProgramCategory: [small stored procedure value]
My question is how do I get the 4 data items from this stored procedure into their respective columns within the dataset that is returned from the large stored procedure?
Using a table-valued function instead of a stored procedure could be helpful. You will be able to use the TVF just like a table ie:
SELECT
COLUMNS_NAMES
FROM
TVF(PARAMS)
As your small stored procedure doesn't write anything, you could just write it as a table valued function.
You can then apply the function to an entire data-set by using APPLY.
(Table valued functions that are written INLINE (not multi-statement) are then explanded macro-like to execute extremely efficiently. This is perfect for your description as the function would just be a single SELECT statement already.)
The Function:
CREATE FUNCTION dbo.your_function(#user_id AS INT)
RETURNS TABLE
AS
RETURN
<your query>
The function used in a query inside your big SP:
SELECT
...,
user_detail.field,
user_detail.degree,
user_detail.degreeyear,
user_detail.programcategory
FROM
...
CROSS APPLY
dbo.your_function(some_table.user_id) AS user_detail
In general I use functions to encapsulate queries, and only wrap them up in Stored Procedures if...
1) I need to write data. (Functions can't INSERT, UPDATE or DELETE)
2) I want to create an API like interface to client applications.
Since you're getting only one row with four values you could use OUTPUT parameters:
EXECUTE SomeSmallerProcedure
#field OUTPUT, #degree OUTPUT, #degreeyear OUTPUT, #ProgramCategory OUTPUT;
Your procedure listed above would change to:
ALTER PROCEDURE SomeSmallerProcedure
#field varchar(255) OUTPUT,
#degree varchar(255) OUTPUT,
#degreeyear varchar(255) OUTPUT,
#ProgramCategory varchar(255) OUTPUT
AS BEGIN SET NOCOUNT ON;
SELECT TOP 1
#field = wea.field,
#degree = wea.degree,
#degreeyear = wea.degreeyear,
#ProgramCategory = wpp.ProgramCategory
-- ... rest as before
The signature of your procedure above would have to include those parameters explicitly for OUTPUT.

TSQL: Call a stored procedure from another stored procedure and read the result

I have a stored procedure that, ending with a SELECT, returns a recordset. I can call it within anoher stored procedure like this:
EXEC procedure #param
How to get the returning recordset? Thanks
You can create a temp table and then use INSERT INTO #MyTable EXEC procedure #param.
There are some other techniques listed here.
AFAIK, you can't. What you probably want to do is use a function for your first (or both) procedures. Functions can only return one thing, but they can return a table. Stored procedures can return multiple results, but not to other functions/stored procedures.
e.g.:
CREATE FUNCTION [dbo].[fn_GetSubordinates] (
#sPersonID VARCHAR(10),
#nLevels INT
)
RETURNS #tblSubordinates TABLE
(
Person_Id VARCHAR(10),
Surname char(25),
Firstname char(25)
)
AS
BEGIN
...
If you are using SQL Server 2008, I would recommend returning a Table-Valued Parameter.
http://msdn.microsoft.com/en-us/library/bb510489.aspx
You can do this with an output variable in the stored proc. For example:
CREATE PROCEDURE sp_HelloWorld #MyReturnValue int OUT
AS
SELECT #MyReturnValue = 100
Return #MyReturnValue
To call this stored proc, do the following:
DECLARE #TestReturnVal int
EXEC sp_HelloWorld #TestReturnVal output
SELECT #TestReturnVal
First, you CANNOT RETURN a recordset by stored procedure. By return, a stored procedure can only return integers.
You mentioned SELECT statement, which is a DQL and just for display purpose.
The way you can do to work around this issue is that you can assign the recordset to a global temporary table which can also be accessed within the outer stored procedure.