Why my stored procedure is always receiving NULL parameters? - sql-server

I've created a T-SQL script which works very well when I execute it directly. Then I've put this script into a stored procedure with 2 parameters but when I execute it, there is no rows affected... then I've found my 2 parameters are always received as NULL by my stored procedure.
I've tried to set default parameters values inside the create stored procedure script, but even that way, they are NULL.
I've tried to not declare the parameters as scalar variable inside the #SQLString since they already are created with the CREATE PROCEDURE as parameters but I got the error :
The scalar variable must be declared
when I tried to execute my stored procedure.
CREATE PROCEDURE [dbo].[sp_InsertMetierEventRelation]
#metier NVARCHAR(50),
#evenement NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQLString NVARCHAR(4000)
SET #SQLString = N'
DECLARE #rowId INT, #metier NVARCHAR(50), #evenement NVARCHAR(50)
SELECT #metier AS metierParam -- always NULL
SELECT #evenement AS evenementParam -- always NULL
SELECT met_id FROM [dbo].[t_metier] WHERE [met_nom] = #metier
SELECT eve_id FROM [dbo].[t_evenement] WHERE [eve_nom] = #evenement
-- some other code
'
EXECUTE sp_executesql #SQLString
END
GO
I call my stored procedure this way :
EXEC [dbo].[sp_InsertMetierEventRelation]
#metier = 'Organisation de mariage',
#evenement = 'Evènement religieux';
or this way :
EXEC [dbo].[sp_InsertMetierEventRelation]
'Organisation de mariage', 'Evènement religieux';
I got the same result :
metierParam NULL
evenementParam NULL
met_id NO RESULT
eve_id NO RESULT

Do you need dynamic SQL? What happens if you simplify it as:
CREATE PROCEDURE [dbo].[sp_InsertMetierEventRelation]
#metier NVARCHAR(50),
#evenement NVARCHAR(50)
AS
SELECT met_id FROM [dbo].[t_metier] WHERE [met_nom] = #metier
SELECT eve_id FROM [dbo].[t_evenement] WHERE [eve_nom] = #evenement
And then run the EXEC [dbo].[sp_InsertMetierEventRelation] ...
If you do need dynamic SQL then see answer from John Cappelletti.

Related

Stored Procedure within a Stored Procedure NVARCHAR output value

I have one stored procedure which return a nvarchar value written like that:
ALTER PROCEDURE [dbo].[GetLastVouchNumber]
#returnVal nvarchar(255) output
AS
BEGIN
SET #returnVal = ( SELECT CONCAT('I',VOUCHNO+1)
FROM TABVOU
WHERE VOUCHER = 'VOUCHER#')
END
I am trying to use the output value from this procedure in another procedure. And this was how I try to write this new procedure:
ALTER PROCEDURE [dbo].[MassAdjInsertIntoYTDTRNI]
#inputPeriod nvarchar(255),
#inputUserId nvarchar(255)
AS
BEGIN
DECLARE #resultOrdNo nvarchar (255)
DECLARE #newOrdNo nvarchar(255)
EXEC #newOrdNo = GetLastVouchNumber #resultOrdNo
INSERT INTO YTDTRNI(TRCDE,PROD,WH,DESCR,UCOST,TCOST,DRAC,CRAC,REM,QTY,UM,ORDNO,TRDATE,SYSDATE,PERIOD,USERID)
SELECT 'AJ',PROD,WH,DESCR,0,-TCOST,STKGL,COSGL,'MASS ADJUSTMENT',0,UM,#newOrdNo, GETDATE(),GETDATE(),#inputPeriod,#inputUserId
FROM INV
I was assuming that this line:
EXEC #newOrdNo = GetLastVouchNumber #resultOrdNo
will store the result of the first procedure into #newOrdNo then after that I can use this #newOrdNo to insert it into another table. But after I execute this second stored procedure, the ORDNO column does not contain any values...
Need advice.
Use OUTPUT keyword when you call GetLastVouchNumber and pass #newOrdNo as an output parameter. Your GetLastVouchNumber procedure returns information with output parameter.
ALTER PROCEDURE [dbo].[MassAdjInsertIntoYTDTRNI]
#inputPeriod nvarchar(255),
#inputUserId nvarchar(255)
AS
BEGIN
DECLARE #resultOrdNo nvarchar (255)
DECLARE #newOrdNo nvarchar(255)
-- Call your stored procedure
EXEC GetLastVouchNumber #newOrdNo OUTPUT
INSERT INTO YTDTRNI(TRCDE,PROD,WH,DESCR,UCOST,TCOST,DRAC,CRAC,REM,QTY,UM,ORDNO,TRDATE,SYSDATE,PERIOD,USERID)
SELECT 'AJ',PROD,WH,DESCR,0,-TCOST,STKGL,COSGL,'MASS ADJUSTMENT',0,UM,#newOrdNo, GETDATE(),GETDATE(),#inputPeriod,#inputUserId
END
You seemed to have confused a return value and an output variable. Your stored proc uses the latter for returning your value, and does not explicitly return anything (Albeit confusing, as you have named your output variable returnVal).
When you call it, you must specify the OUTPUT
EXEC GetLastVouchNumber #resultOrdNo OUTPUT

SQL stored procedure - table as parameter

I have a database with different tables (all the same structure) where I'd like to run a stored procedure having a parameter that defines which table to query.
I can't seem to figure it out:
CREATE SCHEMA test;
GO
First I created a schema
CREATE TYPE DataType as TABLE (
[datetime] [datetime] NULL,
[testVar] [bigint] NULL)
GO
Then I created the table type
USE [TestDataFiles]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [test].[testing]
(
-- Add the parameters for the stored procedure here
#datetime datetime,
#t DataType READONLY
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
select top(10) *
from #t
where [datetime] > #datetime
END
GO
Then I created the stored procedure.
Exec test.testing #t = 'table.1', #datetime = '2017-01-01'
However when I call it I get the following error:
Msg 206, Level 16, State 2, Procedure test, Line 0 [Batch Start Line 0]
Operand type clash: varchar is incompatible with DataType
Same happens with:
Exec test.testing #t = [table.1], #datetime = '2017-01-01'
I have seen an example where in the procedure between the begin and select you put something like:
INSERT INTO table.1
( datetime, testVar)
But table.1 (or table.2 etc as I have a list of tables) has data and I don't want to change it.
Unless I'm meant to create a dummy table like I did the TYPE?
The examples I've found online havent been useful.
To do that you will need to use dynamic SQL
The basic procedure is to build up a string that will hold the statement you will execute, then execute it
declare #SQL nvarchar(1000)
declare #t as nvarchar (1000)
set #t = 'MyTable'
set #Sql = 'Select * from ' + #t
exec sp_executesql #sql
You have to pass parameter of type DataType. So, create variable of that type and pass it into stored procedure like
declare #table1 DataType
INSERT INTO #table1(datetime, testVar) values (..., ...)
Exec test.testing #datetime = '2017-01-01', #t = #table1

TSQL Stored Procedure retrieve variables

I was wondering if it's possible to retrieve the results of a stored procedure using another stored procedure.
I have the following as a test example
The first stored procedure is intended to return two values
if(object_id('sp_function01')) is not null
drop procedure sp_function01
go
create procedure sp_function01
as
declare #lv_res01 char(20)
declare #lv_res02 char(20)
set #lv_res01 = 'fn01 result 01'
set #lv_res02 = 'fn01 result 02'
select #lv_res01, #lv_res02
go
Then the second is intended to retrieve those values and utilize them
if(object_id('sp_function02')) is not null
drop procedure sp_function02
go
create procedure sp_function02
as
declare #lv_var01 char(20)
declare #lv_res01 char(20)
declare #lv_res02 char(20)
set #lv_var01 = 'variable 01'
exec sp_function01
-- catch variables from this function
-- into lv_res01 and lv_res02
select #lv_var01, #lv_res01, #lv_res02
go
Yet the values for lv_res01 and lv_res02 are NULL and I'm not sure how to actually catch them
Something like this:
First procedure:
create procedure sp_function01
#lv_res01 char(20) OUTPUT,
#lv_res02 char(20) OUTPUT
as
set #lv_res01 = 'fn01 result 01'
set #lv_res02 = 'fn01 result 02'
select #lv_res01, #lv_res02
go
Second procedure:
create procedure sp_function02
as
declare #lv_var01 char(20)
declare #lv_res01 char(20)
declare #lv_res02 char(20)
set #lv_var01 = 'variable 01'
exec sp_function01 #lv_res01 OUTPUT, #lv_res02 OUTPUT
-- catch variables from this function
-- into lv_res01 and lv_res02
select #lv_var01, #lv_res01, #lv_res02
go
Calling sp_function01 alone (it's more or less same you just need to declare all output parameters and pass them to proc whether from inside another stored procedure or outside of it):
DECLARE #lv_res01 char(20)
DECLARE #lv_res02 char(20)
exec sp_function01 #lv_res01 OUTPUT, #lv_res02 OUTPUT
The scope of local variables is the module in which they are declared so the variables in function02 are not available in function one. You need to either use OUTPUT parameters or use the INSERT...EXEC to insert the result set of function02 into a temp table or table variable.
See how to share data between stored procedures for a thorough discussion of these and other options.

SQL Server: how to create a stored procedure

I'm learning sql from a book and I'm trying to write a stored procedure but I don't believe that I'm doing it correctly. Is the following way not valid in Microsoft SQL? If not, when is it valid, if ever?
create procedure dept_count(in dept_name varchar(20), out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
I get the following error
Msg 156, Level 15, State 1, Procedure wine_change, Line 1
Incorrect syntax near the keyword 'in'.
T-SQL
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
CREATE PROCEDURE GetstudentnameInOutputVariable
(
#studentid INT, --Input parameter , Studentid of the student
#studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
#StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT #studentname= Firstname+' '+Lastname,
#StudentEmail=email FROM tbl_Students WHERE studentid=#studentid
END
In T-SQL stored procedures for input parameters explicit 'in' keyword is not required and for output parameters an explicit 'Output' keyword is required. The query in question can be written as:
CREATE PROCEDURE dept_count
(
-- Add input and output parameters for the stored procedure here
#dept_name varchar(20), --Input parameter
#d_count int OUTPUT -- Output parameter declared with the help of OUTPUT/OUT keyword
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Statements for procedure here
SELECT #d_count = count(*)
from instructor
where instructor.dept_name=#dept_name
END
GO
and to execute above procedure we can write as:
Declare #dept_name varchar(20), -- Declaring the variable to collect the dept_name
#d_count int -- Declaring the variable to collect the d_count
SET #dept_name = 'Test'
Execute dept_count #dept_name,#d_count output
SELECT #d_count -- "Select" Statement is used to show the output
I think it can help you:
CREATE PROCEDURE DEPT_COUNT
(
#DEPT_NAME VARCHAR(20), -- Input parameter
#D_COUNT INT OUTPUT -- Output parameter
-- Remember parameters begin with "#"
)
AS -- You miss this word in your example
BEGIN
SELECT COUNT(*)
INTO #D_COUNT -- Into a Temp Table (prefix "#")
FROM INSTRUCTOR
WHERE INSTRUCTOR.DEPT_NAME = DEPT_COUNT.DEPT_NAME
END
Then, you can call the SP like this way, for example:
DECLARE #COUNTER INT
EXEC DEPT_COUNT 'DeptName', #COUNTER OUTPUT
SELECT #COUNTER
Try this:
create procedure dept_count(#dept_name varchar(20),#d_count int)
begin
set #d_count=(select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name)
Select #d_count as count
end
Or
create procedure dept_count(#dept_name varchar(20))
begin
select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name
end
CREATE PROCEDURE [dbo].[USP_StudentInformation]
#S_Name VARCHAR(50)
,#S_Address VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Date VARCHAR(50)
SET #Date = GETDATE()
IF EXISTS (
SELECT *
FROM TB_StdFunction
WHERE S_Name = #S_Name
AND S_Address = #S_Address
)
BEGIN
UPDATE TB_StdFunction
SET S_Name = #S_Name
,S_Address = #S_Address
,ModifiedDate = #Date
WHERE S_Name = #S_Name
AND S_Address = #S_Address
SELECT *
FROM TB_StdFunction
END
ELSE
BEGIN
INSERT INTO TB_StdFunction (
S_Name
,S_Address
,CreatedDate
)
VALUES (
#S_Name
,#S_Address
,#date
)
SELECT *
FROM TB_StdFunction
END
END
Table Name : TB_StdFunction
S_No INT PRIMARY KEY AUTO_INCREMENT
S_Name nvarchar(50)
S_Address nvarchar(500)
CreatedDate nvarchar(50)
ModifiedDate nvarchar(50)
Create this way.
Create procedure dept_count(dept_name varchar(20),d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
try this:
create procedure dept_count( #dept_name varchar(20), #d_count INTEGER out)
AS
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
To Create SQL server Store procedure in SQL server management studio
Expand your database
Expand programmatically
Right-click on Stored-procedure and Select "new Stored Procedure"
Now, Write your Store procedure, for example, it can be something like below
USE DatabaseName;
GO
CREATE PROCEDURE ProcedureName
#LastName nvarchar(50),
#FirstName nvarchar(50)
AS
SET NOCOUNT ON;
//Your SQL query here, like
Select FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = #FirstName AND LastName = #LastName
GO
Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (#LastName and #FirstName) and type = parameter type example nvarchar(50) etc.
Source: Stored procedure in sql server (With Example)
To Execute the above stored procedure you can use sample query as below
EXECUTE ProcedureName #FirstName = N'Pilar', #LastName = N'Ackerman';

SQL Server - Trouble passing variable to a stored procedure

I know this is a basic question - but I can't figure the correct way to get this done.
I need to pass a variable to a SQL Server 2008 stored procedure and return the query.
Here's the stored procedure:
CREATE PROCEDURE pOrders
AS
DECLARE #enteredClientID varchar(20);
DECLARE #Results table (ClientID varchar(20), Num_orders int);
BEGIN
SET NOCOUNT ON;
-- Get all the order from the client
INSERT INTO #Results
SELECT ClientID, sum(Num_orders)
FROM Orders O
WHERE O.ClientID = #enteredClientID
GROUP BY O.ClientID);
-- Insert the orders into the results table --
SELECT *
FROM #Results;
END
GO;
Now, I would execute the stored procedure and get the result back:
exec pOrders
set #enteredClientID = 'ABC123456789'
I get this error message back:
Must declare the scalar variable "#enteredClientID".
But, I'm declaring the variable.... what am I missing?
You didn't declare a parameter, but a local variable. To declare it as you wanted to:
CREATE PROCEDURE pOrders (#enteredClientID varchar(20))
AS
DECLARE #Results table (ClientID varchar(20), Num_orders int);
SET NOCOUNT ON;
-- Get all the order from the client
INSERT INTO #Results
SELECT ClientID, sum(Num_orders)
FROM Orders O
WHERE O.ClientID = #enteredClientID
GROUP BY O.ClientID);
-- Insert the orders into the results table --
SELECT *
FROM #Results;
GO;
An to call it:
exec pOrders #enteredClientID = 'ABC123456789'
or simply
exec pOrders 'ABC123456789'
--In stored proc
DECLARE #enteredClientID varchar(20) OUTPUT
--Then insert and set identity
SELECT SCOPE_IDENTITY() AS #enteredClientID
--When calling procedure:
-- DECLARE variables to hold the return value
DECLARE #enteredClientID VARCHAR(20);
-- Execute the procedure, which returns value.
EXEC #enteredClientID = pOrders
Try EXEC pOrders 'ABC123456789'.
The call you provided attempts to execute the procedure (with no parameters passed), then attempts to set a variable named #enteredClientID. Since you have not declared #enteredClientID in the scope of the executing code, it cannot set it.
For more information about how to use parameters with procedures, this article may be helpful:
http://msdn.microsoft.com/en-us/library/ms189915.aspx

Resources