How to use optional parameter in stored procedure - sql

I have a stored procedure which looks like
CREATE PROCEDURE Update-all
( #RowID INT,
#Parameter1 NVARCHAR(50),
#Parameter2 INT
)
As
....
i will be passing #Parameter1 / #Parameter2 based on different conditions.
if i don't pass #Parameter1 / #Parameter2 ,i am getting a error the stored procedure expects #parameter1/#parameter1 which is not supplied . Any ideas how to fix this issue?

You need to supply default values for the parameters.
CREATE PROCEDURE Update-all
( #RowID INT,
#Parameter1 NVARCHAR(50) = NULL,
#Parameter2 INT = NULL
)
As
....

You need to provide defaults for your parameters. e.g.
create procedure Test1 (
#rowid int,
#Param1 nvarchar(50) = null,
#Param2 int = 0 )
as
print 'rowid=' + convert(varchar(20), #rowid)
print 'param1=' + #Param1
print 'param2=' + convert(varchar(20), #Param2)
exec Test1 5
exec Test1 5, 'testing'
exec Test1 5, 'testing', 198

Add some default values to parameters:
CREATE PROCEDURE Update-all
( #RowID INT,
#Parameter1 NVARCHAR(50) = '',
#Parameter2 INT = 0
)

Related

Get result parameter of stored procedure in exec clause

I have a stored procedure that returns multiple parameters:
CREATE PROCEDURE [dbo].[TestSP]
#Test1 INT
, #Test2 UNIQUEIDENTIFIER
--some inserts and alters here
SELECT TOP 1
#Parameter1 AS Design
, #Parameter2
, #Parameter3
FROM Table
I want to use EXEC into another stored procedure and get ONLY #Parameter1 (Design)
So I want to get #Parameter1 after EXEC stored procedure, so I think about OUTPUT, but it doesn't work, is there a way to achieve this?
CREATE PROCEDURE [dbo].[SecondStoredProcedure]
#Sender1 INT
, #Sender2 UNIQUEIDENTIFIER
DECLARE #ReturnedParameter1 INT
EXEC [dbo].[TestSP] #Test1 = #Sender1, #Test2 = #Sender2 OUTPUT [Design]
INTO #ReturnedParameter1
SELECT #ReturnedParameter1
That procedure creates a resultset, and has no output parameters. You can capture a resultset with insert into ... exec, like this:
use tempdb
go
CREATE PROCEDURE [dbo].[addDesign]
#Test1 INT
,#Test2 UNIQUEIDENTIFIER
as
begin
--some inserts and alters here
SELECT
1 AS Design
, 2 as Foo
, 3 as Bar
end
go
declare #rv table(Design int, Foo int, Bar int)
declare #test2 uniqueidentifier = newid()
insert into #rv
exec addDesign 1, #test2
declare #design int = (select Design from #rv)
select #design
I suggest using an output parameter as explained in the official docs.
Here is how your code might look in this case:
use tempdb
go
create procedure [dbo].[addDesign]
(
#Test1 int
, #Test2 uniqueidentifier
, #Design int out
)
as
begin
set nocount on;
--some inserts and alters here
-- Set the return parameter
set #Design = #Parameter1;
-- Select the return results
SELECT TOP 1
#Parameter1
, #Parameter2
, #Parameter3
FROM dbo.MyTable;
-- Return status code, proc ran OK
return 0;
end
go
create procedure [dbo].[SecondStoredProcedure]
(
#Sender1 int
, #Sender2 uniqueidentifier
)
as
begin
set nocount on;
declare #ReturnedParameter1 int;
exec dbo.TestSP #Test1 = #Sender1, #Test2 = #Sender2, #Design = #ReturnedParameter1;
select #ReturnedParameter1;
-- Return status code, proc ran OK
return 0;
end
go
Note: This demonstrates the 3 ways information can be returned from a stored procedure, the result code (only 1), output parameters (0-N) and result sets (0-N).

Stored procedured doesnt give the result back

I have written such a stored procedure, it must return a result, but it doesnt do that. it returns only a message that stored procedure runs successfully.
How should I change my SP?
CREATE PROCEDURE TestTVP
(
#param1 int,
#param2 int,
#a int OUTPUT
)
as
SET NOCOUNT ON
DECLARE #T1 as TABLE
(
PK INT IDENTITY NOT NULL,
Wert INTEGER,
Name INTEGER
)
INSERT INTO #T1(Wert,Name) VALUES (#param1,#param2)
return select count(*) from #T1
GO
exec TestTVP '1','22'
you have to pass OUTPUT parameter
declare #z int
exec TestTVP '1','22' ,#z output
and remove return from Stored Procedure make it only
...
select count(*) from #T1
You can use out parameter if you want the output :
DECLARE #Z int
EXEC TestTVP '2', '22',#z out

SQL call a SP from another SP

Can I please have some help with the syntax of a SP in SQL.
Here is my code:
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10)
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertValue
(
#ID VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #v_Value VARCHAR(15)
Set #v_Value = usp_GetValue(#ID, #Description)
END
In the usp_InsertValue SP, I am wanting to declare and set a variable. Once the variable has been declared, I then wish to call another SP with parameters to set the value of the declared variable.
I am not sure of the syntax. May I please have some help?
UPDATE
I have updated my above code using your function. How do I Set the #v_Value from the usp_GetValue function.
I am getting this error:
'usp_GetValue' is not a recognized built-in function name.
UPDATE2
Here is my full code:
CREATE PROCEDURE usp_PersonCategoryLookupTesting
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#res VARCHAR(10) OUTPUT
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertPersonTesting
(
#IDTest VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#AddressLine1 VARCHAR(50),
#AddressLine2 VARCHAR(50),
#AddressLine3 VARCHAR(50),
#MobilePhone VARCHAR(20),
#HomePhone VARCHAR(20),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #PersonCategory VARCHAR(15)
EXEC usp_PersonCategoryLookupTest #ID, #Description, #PersonCategory
INSERT INTO Person(FirstName, LastName, AddressLine1, AddressLine2, AddressLine3, MobilePhone, HomePhone, DateModified, PersonCategory, Comment)
VALUES (#FirstName, #LastName, #AddressLine1, #AddressLine2, #AddressLine3, #MobilePhone, #HomePhone, GETDATE (), #PersonCategory, #Comment)
END
I am getting this error in my application that is calling the SQL code:
Conversion failed when converting the varchar value '123Client' to data type int.
I am using the values "123" and "Client" for #IDTest and #Description.
I think output parameters should be the proper way:
See this post:
stored procedure returns varchar
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#res VARCHAR(10) OUTPUT
)
AS
BEGIN
return #ID + #Description
END
CREATE PROCEDURE usp_InsertValue
(
#ID VARCHAR(10),
#FirstName VARCHAR(50),
#LastName VARCHAR(50),
#Description VARCHAR(10),
#Comment VARCHAR(max)
)
AS
BEGIN
Declare #v_Value VARCHAR(15)
EXEC usp_GetValue #ID, #Description, #v_Value
-- use #v_Value here...
END
You can only use a function like that, not stored procedure. Stored Procedures only return integer values.
For SP, you need to create out parameters to retrieve the values. For this scenario, it is better to create a function
CREATE FUNCTION usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
)
RETURNS VARCHAR(50)
AS
BEGIN
return #ID + #Description
END
Then call it:
SET #v_value = dbo.usp_GetValue('John','Doe') --output: John Doe
If you insist you want a SP, which is not proper for this, there are 2 ways
1) An out parameter
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10),
#Result varchar(20) OUTPUT
)
AS
BEGIN
SET #Result = #ID + #Description
END
Then call it:
Declare #v_Value VARCHAR(15)
Set #v_Value = EXEC usp_GetValue #ID, #Description, #v_Value OUTPUT
2) Select from it
CREATE PROCEDURE usp_GetValue
(
#ID VARCHAR(10),
#Description VARCHAR(10)
)
AS
BEGIN
SELECT #ID + #Description
END
Use it like this:
declare #tempresult as table(v_value as varchar(15))
INSERT INTO #tempresult
EXEC usp_GetValue #ID, #Description
Select Top 1 #v_value = v_value From #tempresult
My advise is use the function approach.

How to pass values from SP to SP?

I have a question, I have a Stored Procedure which returns a value. This Stored Procedure is being executed within another SP and I need to transfer the value into this SP. How can I accomplish this.
Any help will be appreciated.
Thank you
Example:
CREATE PROC [dbo].[isp_CREATE_CONFIG]
#CFG_KEY VARCHAR(15)
, #CFG_SHORTVALUE INT
, #CFG_LONGVALUE VARCHAR(200)
, #CFG_DESC VARCHAR(250)
, #CFG_SHORT_DESC VARCHAR(100)
, #CFG_MISC1 VARCHAR(50)
, #CFG_MISC2 VARCHAR(50)
, #CFG_MISC3 VARCHAR(50)
, #CFG_MISC4 VARCHAR(50)
, #CFG_MISC5 VARCHAR(50)
, #CFG_USER VARCHAR(20)
, #CFG_MSG VARCHAR(250) OUTPUT
AS
DECLARE
#c_ErrMsg VARCHAR(200)
, #c_ErrNum VARCHAR(5)
, #c_Continue INT
, #c_Date VARCHAR(20)
/* Assign value to local variables */
SET #c_Date = GETDATE()
SET #c_Continue = 0
/* Run Validations */
IF EXISTS (SELECT 1 FROM CONFIG(NOLOCK) WHERE cfg_key = #CFG_KEY)
BEGIN
SET #c_ErrNum = 60001
SET #c_ErrMsg = 'Configuration Key (' + #CFG_KEY + ') already exist. Please check System Configuration. Error: ' + #c_ErrNum
SET #CFG_MSG = #c_ErrMsg
SET #c_Continue = 1
END
/* Create Configuration */
SET #CFG_MSG = ''
IF #c_Continue = 0
BEGIN
IF NOT EXISTS(SELECT 1 FROM CONFIG(NOLOCK) WHERE cfg_key = #CFG_KEY)
BEGIN
INSERT INTO CONFIG
(
cfg_key , cfg_short_value , cfg_long_value , cfg_desc ,cfg_short_desc
, cfg_misc1 , cfg_misc2 , cfg_misc3 , cfg_misc4
, cfg_misc5 , cfg_add_who , cfg_edit_date , cfg_edit_who
)
VALUES
(
#CFG_KEY , #CFG_SHORTVALUE , #CFG_LONGVALUE , #CFG_DESC , #CFG_SHORT_DESC
, #CFG_MISC1 , #CFG_MISC2 , #CFG_MISC3 , #CFG_MISC4
, #CFG_MISC5 , #CFG_USER , #c_Date , #CFG_USER
)
SET #CFG_MSG = 'Configuration has been created.'
END
END
GO
Your stored procedure that returns the value has a parameter declared as OUTPUT, something like this:
CREATE PROCEDURE my_returning_proc (#ret VARCHAR(10) OUTPUT) AS
BEGIN .... END
If you want to use this value you need to call the STORED PROCEDURE like this:
DECLARE #var VARCHAR(10);
EXEC my_returning_proc #var OUTPUT;
PRINT #var
The key's here is to add OUTPUT into EXEC statement
EDIT: Thanks for providing example.
For your case you would call the stored procedure like this:
DECLARE #var_returned VARCHAR(250);
EXEC [dbo].[isp_CREATE_CONFIG] 'BLAH', 0, 'BLAH', 'BLAH', 'BLAH', ......, #var_returned OUTPUT
By return a value, I assume you mean using return. You can also declare output parameters for the stored procedure.
Here is how:
declare #retval int;
exec #retval = <stored procedure call>
Here is a simple code sample anyone can try:
create procedure dum as return 5
declare #retval int;
exec #retval = dum
select #retval
I use this technique all the time to return status from stored procedures.

SQL Server: Return uniqueidentifier from stored procedure

Can I return UNIQUEIDENTIFIER from a stored procedure using the RETURN statement or is it only by using the OUTPUT statement?
i.e to return the PersonID UNIQUEIDENTIFIER:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT
AS
DECLARE #Count INT
DECLARE #JobFileGUID UNIQUEIDENTIFIER
-- Check if job exists?
SET #Count = (SELECT COUNT(Name) AS Name FROM Person WHERE Name=#Name)
IF #Count < 1
BEGIN
SET #PersonGUID = NEWID();
INSERT INTO Person
(PersonID, Name, [Desc])
VALUES (#PersonGUID, #Name, #Desc)
END
SELECT #PersonGUID = Person.PersonID
FROM Person
WHERE Name = #Name
RETURN #PersonGUID
GO
Thanks
In stored procedure - only using the OUTPUT statement. In function - return.
Use:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT,
#PersonGUID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #PersonGUID = ...
END
How to call:
DECLARE
#name NVARCHAR(255),
#desc TEXT,
#personGUID UNIQUEIDENTIFIER
SET #name = 'Bob'
SET #desc = 'One handsome man.'
EXEC [Database].[schema].CreatePerson #name, #desc, #personGUID OUTPUT
From the documentation you can actually see that a return in a stored procedure is actually used as a response code, hence you get the exception when trying to return a uniqueidentifier.
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-ver16#return-data-using-a-return-code
How I solved it, is by just performing a SELECT after the insert of the generated unique identifier.
DECLARE #ReportId UNIQUEIDENTIFIER;
SET #ReportId = NEWID();
INSERT INTO [dbo].[Report]
([ReportId]
,[ReportName])
VALUES
(#ReportId
,#ReportName)
SELECT #ReportId as ReportIdInternal
You'll have to see how to perform that with multiple selects though.
CREATE TABLE [dbo].[tbl_Clients]( [ClientID] [uniqueidentifier] NULL, [ClientName] varchar NULL, [ClientEnabled] [bit] NULL ) ON [PRIMARY]
GO
CREATE PROCEDURE [dbo].[sp_ClientCreate] #in_ClientName varchar(250) = "New Client 123", #in_ClientEnabled bit, #out_ClientId uniqueidentifier OUTPUT AS
SET #out_ClientId = NEWID();
INSERT INTO tbl_Clients(ClientId, ClientName, ClientEnabled) VALUES( #out_ClientId, #in_ClientName, #in_ClientEnabled)
DECLARE #return_value int, #out_ClientId uniqueidentifier
EXEC #return_value = [dbo].[sp_ClientCreate] #in_ClientName = N'111', #in_ClientEnabled = 1, #out_ClientId = #out_ClientId OUTPUT
SELECT #out_ClientId as N'#out_ClientId'
SELECT 'Return Value' = #return_value
GO
Result:-59A6D7FE-8C9A-4ED3-8FC6-31A989CCC8DB