I have a T-SQL stored procedure with the following parameters
CREATE PROCEDURE [dbo].[SaveData] -- Add the parameters for the stored procedure here @UserID varchar(50), @ServiceID varchar(50), @param1 varchar(50), @param2 varchar(50), @endDate datetime AS BEGIN . . -- my code --
I want know if it is possible to pass a result of select
as parameter:
exec SaveDate (SELECT player.UserID,player.ServiceID, 'no','no',GETDATE() FROM player)
I tried something like this, but it does not work.
CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.
The Output Parameters in Stored Procedures are used to return some value or values. A Stored Procedure can have any number of output parameters. The simple logic is this — If you want to return 1 value then use 1 output parameter, for returning 5 values use 5 output parameters, for 10 use 10, and so on.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.
This provides a way to save a result returned from one query, then refer to it later in other queries. The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving.
1.One way is:
a) Declare your variables
b) Assign values to them with a single select statement
c) Execute the procedure passing the local variables
d) Execute the following in a loop using WHILE or CURSOR in order to apply this for all rows in TABLE1
DECLARE @param1 <DATATYPE>, @param2 <DATATYPE>, ... SELECT TOP 1 @param1 = col1, @param2 = col2, ... FROM TABLE1 WHERE <where_clause> EXEC SaveDate @param1, @param2, ...
2.Other way is to define your own table type, fill it, and pass it to procedure. However this requires changing a little bit your stored procedure (in params list your custom type should be followed by READONLY
):
CREATE TYPE [dbo].[TYPENAME] AS TABLE( [ID] [int] NOT NULL, ... ) GO DECLARE @myTypeVar TYPENAME; INSERT @myTypeVar SELECT col1, col2, ... FROM TABLE1 EXEC SaveData @myTypeVar
The SELECT query you wrote in your example would probably bring back multiple rows (your SELECT does not feature a WHERE clause or a TOP(n)). If your intention is to be able to have your procedure engage a "tabular" set of parameters, from SQL Server 2008, you are able to use table valued parameters.
This involves creating a user defined table table and will almost undoubtedly mean adjusting the logic inside the stored procedure.
Hope this helps :)
See http://msdn.microsoft.com/en-us/library/bb510489(SQL.100).aspx for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With