Storing one or several sql statements as a variable in a stored procedure in SQL Server - sql

Let's say I have a stored procedure. Is it possible to store multiple sql statements in a variable inside a stored procedure and later execute it when the procedure is invoked?
Example:
CREATE PROCEDURE dbo.StoredProcedure
(
#parameter1 int = QUERIES_HERE
)
AS
/*something like execute #parameter1*/
RETURN

Yes, like this:
DECLARE #SQLQuery varchar(500)
SET #SQLQuery = 'SELECT * FROM Employees WHERE EmployeeID = 123'
EXECUTE(#SQLQuery)

Related

Dynamically get all parameter values in stored procedure

Is there any way to get all parameter values from a stored procedure dynamically?
In other words, iterate through all parameters in one stored procedure to get their values into one string. This is for a unified logging process for a bunch of stored procedures.
I can get the names of parameters:
SELECT PARAMETER_NAME
FROM INFORMATION_SCHEMA.PARAMETER
WHERE SPECIFIC_NAME = 'procedure_name';
Also, I tried to use dynamic SQL commands. I've generated a command with included parameter, but EXEC can't execute command.
#cmd = 'SELECT '#UserID' + CONVERT(NVARCHAR(MAX), #UserID)
+ '#Date' + CONVERT(NVARCHAR(MAX), #Date)'
EXEC #cmd
Is there any way to do this besides manually generating a list of parameter values for each stored procedure?
Since SQL Server 2014 there is sys.dm_exec_input_buffer a table valued function with an output column event_info that gives the full execution statement (including parameters).
I use this for error logging in stored procedures.
For example:
--include this inside the stored procedure
declare #statement nvarchar(max)
select #statement = event_info
from sys.dm_exec_input_buffer(##spid, current_request_id())
--this will print whatever you called the procedure with (including parameters)
print #statement
-- if you want to parse just the parameters from the statement, it can be done like this
declare #proc_name varchar(128) = object_name(##procid)
declare #param_idx int = charindex(#proc_name, #statement) + len(#proc_name)
declare #param_len int = len(#statement) - #param_idx
declare #params nvarchar(max) = right(#statement, #param_len)
select #params

Calling one stored procedure within another stored procedure using variables from first stored procedure

I have a stored procedure say #Create_Dummy1 which is being passed a variable. This is declared as #Dummy_Variable1 in this stored procedure.
Next I need to call another stored procedure #Create_Dummy2 from #Create_Dummy1. I need to pass #Dummy_Variable1 in the exec statement.
But if I try to do this the string #Dummy_Variable1 is only being passed instead of the value it holds.
I'm executing procedures inside other procedures like this:
DECLARE #childResult int, #loaErrorCode int, #loaErrorMessage varchar(255)
EXEC #childResult = [dbo].[proc_sub_getSomething] #schemes_id = #foo_schemes_i, #errorCode = #loaErrorCode OUTPUT , #errorMessage = #loaErrorMessage OUTPUT
Should it still not work you should edit your question to show your exact code.
This should work:
create procedure Create_Dummy1
(
#Dummy_Variable1 int
)
as
exec Create_Dummy2 #Dummy_Variable1
Go
And
create procedure Create_Dummy2
(
#Dummy_Variable1 int
)
as
Select * From yourTable WHERE tableColumn = #Dummy_Variable1
And this is how you call it:
exec Create_Dummy1 1
Hope this helps.

How to know total record return stored procedure in sql?

I have a stored procedure called usp_getTotalOrder which looks like
Select * from Order where CompanyID = 1;
Now, I have a table which contains stored procedure names.
In my BLL I have a stored procedure name. I want to create function which contain one parameter StoredProcedureName and returns the count of total rows which is like
Declare #str varchar(50)
Set #str='GetOrders'; // Stored Procedure Name
Exec #str
But it does not return total row count that I want to get from the stored procedure with its name in the function.
Any IDEA???
Please help.....
Take a look at ##ROWCOUNT
http://technet.microsoft.com/en-us/library/ms187316.aspx
You might be able to use something like:
Declare #str varchar(50)
Set #str='GetOrders'; // Stored Procedure Name
Exec #str
SELECT ##ROWCOUNT
Do you want to count the number of rows in the result set from the sproc?
In that case you could do:
INSERT INTO #Orders
Exec #str
SELECT COUNT(*)
FROM #Orders
or you could use a Table variable instead of the temp table.
You can return the count of rows by output parameter or return value from your SP. Of course you have to add that output parameter to your SP and set it with COUNT(*) inside the SP.
DECLARE #o_count INT
EXEC GetOrder #o_count = #count OUT

SQL Server Stored Procedure capture return value in T-SQL

I have a SQL Server stored procedure; I need to capture the return value from the stored procedure. Is this the correct way of doing this?
declare valback varchar(30)
set valback = exec storeproc1
In this case, storeproc1 is my stored procedure.
To start, use proper T-SQL syntax:
declare #valback int;
exec #valback = storeproc1;
The only return type allowed for a stored procedure is int. Stored procedures return status via the return statement.
I somehow have a feeling that you really want something else, namely:
to have an OUTPUT parameter in the procedure:
declare #valback varchar(30);
exec storedproc1 #valback OUTPUT;
or capture the procedure result set via INSERT ... EXEC. See How to Share Data Between Stored Procedures.
The correct syntax is:
DECLARE #valback VARCHAR(30)
EXEC #valback = storeproc1
As per the documentation:
http://msdn.microsoft.com/en-us/library/ms188332.aspx

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