Count query doesn't work in store procedure - sql

I am trying to select no of rows returned by select statement, but it returns 0, otherwise if I run simple count query, then it returns no of records being found WHY doesn't SP work for me ???
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE GetUser_Pwd
#EmplID char,
#EmplPwd varchar(50)
As
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #No_Rows int
Select No_Rows= count(*) from HrEmployee where EmplID = #EmplID AND PassWord = #EmplPwd
Return #No_Rows
END
GO
This return 0,
Exec GetUser_Pwd 1, 1234
This returns 1
select count(*) from HrEmployee where EmplID = 1 AND PassWord = 1234

You will need to declare an OUTPUT variable. Try this:
CREATE PROCEDURE GetUser_Pwd
#EmplID char,
#EmplPwd varchar(50),
#No_Rows int OUTPUT
As
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select #No_Rows= count(*)
from HrEmployee
where EmplID = #EmplID AND PassWord = #EmplPwd
RETURN
END
GO
Now, use the following to call the procedure
-- Declare the variable to receive the output value of the procedure.
DECLARE #No_Rows int;
-- Execute the procedure and save the output value in the variable #No_Rows
EXECUTE GetUser_Pwd #EmpId = '1',#EmplPwd='1234',#No_Rows=#No_Rows OUTPUT;
-- Display the value returned by the procedure.
PRINT 'Number of rows matching the criteria is ' +
convert(varchar(10),#No_Rows);
GO

Instead of RETURN #No_Rows write SELECT #No_Rows.
RETURN statement is used for Functions .
For Stored Procedure, RETURN statement is used if you are using OUTPUT paramater.
Read here on how to retrieve result from stored procedure
Declare #No_Rows int
Select #No_Rows= count(*) from HrEmployee where EmplID = #EmplID AND PassWord = #EmplPwd
Select #No_Rows

CREATE PROCEDURE GetUser_Pwd
#EmplID char,
#EmplPwd varchar(50)
As
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #No_Rows int
Select #No_Rows= count(*) from HrEmployee where EmplID = #EmplID AND PassWord = #EmplPwd
Return #No_Rows
END
GO
/Calling Like .../
DECLARE #x INT
EXEC #x = GetUser_Pwd #EmplID=1,#EmplPwd=1
SELECT #x

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).

How can I return tables with different number of parameters with procedure?

I'm going to create different temp tables depending on the #selection parameter I get, and then I want to return the table I created.
I actually wanted to do it with the function, but I got an error for variable parameter tables. The sql procedur I wrote is as follows:
ALTER PROCEDURE [dbo].[Report]
(#Id BIGINT = 55,
#selection INT)
AS
BEGIN
IF #selection=1
BEGIN
Declare #tep_table table (Id int
,Name varchar(250)
,CreateTime datetime
,UpdateTime datetime
,UpdatedBy varchar(250)
,Deleted bit
)
Insert into #tep_table
Select * from User
END
IF #selection=1
BEGIN
Declare #tep_table2 table (Id int
,CreateTime datetime
,UpdateTime datetime
,UpdatedBy varchar(250)
,Deleted bit
)
Insert into #tep_table2
Select * from Client
END
IF #selection=1
BEGIN
RETURN #tep_table
END
ELSE
BEGIN
RETURN #tep_table2
END
END
I am getting this error:
Must declare the scalar variable "#tep_table"
Personally I would turn this into three procedures to avoid the performance problems faced with multiple execution paths.
Something like this.
ALTER Procedure [dbo].[Report]
(
#Id bigint = 55 --not sure what the point of this parameter is as it wasn't used anywhere in the sample code
, #selection int
) AS
set nocount on;
IF #selection = 1
exec GetUserData;
IF #selection = 2
exec GetClientData;
GO
create procedure GetUserData
AS
set nocount on;
Select * --would prefer to use column names here instead of *
from [User];
GO
create procedure GetClientData
AS
set nocount on;
Select * --would prefer to use column names here instead of *
from Client;
GO

sp_executesql sets a column to null

I'm attempting to execute some SQL inside of sp_executesql.
Here is the generated SQL:
exec sp_executesql
N'declare #RC int
EXECUTE #RC = [dbo].[sp_StoredProcedureName]
#parameterName
select #RC',
N'#parameterName nvarchar(4000)',
#parameterName=N'TEST'
Here is the stored procedure that is called from the generated SQL:
ALTER PROCEDURE [dbo].[sp_StoredProcedureName] (
#parameterName varchar(4000)
)
with execute as owner
as
DECLARE #returnValue int
BEGIN TRANSACTION
INSERT INTO [dbo].[TableName]
(parameterName)
VALUES
(#parameterName)
set #returnValue = IDENT_CURRENT('TableName')
COMMIT
SELECT #returnValue
GO
For some reason, parameterName is never set.
When attempting to select from TableName after the SP has been executed, ParameterName is NULL.
I am using MS SQL. The SQL was generated by ADO.NET.
Your stored procedure is not returning anything, hence the return value is NULL.
In general, you should only be using the return value from a stored procedure as a status, not to return actual data.
Real return values should be returned via output parameters.
Further, I strongly recommend an OUTPUT clause for this purpose:
ALTER PROCEDURE [dbo].[sp_StoredProcedureName] (
#parameterName varchar(4000),
#returnValue int OUTPUT
)
with execute as owner
as
BEGIN
DECLARE #ids TABLE (id int);
INSERT INTO [dbo].[TableName] (parameterName)
OUTPUT id INTO #ids
VALUES (#parameterName);
SELECT TOP (1) #returnValue = id -- only 1 is expected anyway
FROM #ids;
END;
You would then call this as:
declare #RC int;
declare #parameterName nvarchar(4000);
set #parameterName = N'TEST';
exec [dbo].[sp_StoredProcedureName] #parameterName, #rc int OUTPUT;
Dynamic SQL is not necessary.

Stored procedure unsure syntax

I am trying to create a stored procedure that will determine if my customerid exists if it exists then my other parameter foundcustomer will be assigned to found otherwise not found. I am unsure how to assign found please help
here is what i tried
CREATE PROCEDURE procedure4
-- Add the parameters for the stored procedure here
#FoundCustomer varchar(10) = null,
#Customerid varchar (5) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
if Not(#Customerid is null)
SELECT customerid
from customers
where customerid = #Customerid
END
GO
Gordon is right, it sounds like you may want a function but if it has to be a stored procedure you can follow this example.
CREATE PROCEDURE procedure4
#Customerid varchar(5) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FoundCustomer varchar(10) = ''
IF #FoundCustomer is not null
BEGIN
IF (SELECT COUNT(1) FROM customers WHERE customerid = #customerid) > 0
SET #FoundCustomer = 'Found'
ELSE
SET #FoundCustomer = 'Not Found'
END
SELECT #FoundCustomer
END

How to return the output of stored procedure into a variable in sql server

I want to execute a stored procedure in SQL Server and assign the output to a variable (it returns a single value) ?
That depends on the nature of the information you want to return.
If it is a single integer value, you can use the return statement
create proc myproc
as
begin
return 1
end
go
declare #i int
exec #i = myproc
If you have a non integer value, or a number of scalar values, you can use output parameters
create proc myproc
#a int output,
#b varchar(50) output
as
begin
select #a = 1, #b='hello'
end
go
declare #i int, #j varchar(50)
exec myproc #i output, #j output
If you want to return a dataset, you can use insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare #t table (name varchar(100))
insert #t (name)
exec myproc
You can even return a cursor but that's just horrid so I shan't give an example :)
You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.
If no return is explicitly set, then the stored procedure returns zero.
CREATE PROCEDURE GetImmediateManager
#employeeID INT,
#managerID INT OUTPUT
AS
BEGIN
SELECT #managerID = ManagerID
FROM HumanResources.Employee
WHERE EmployeeID = #employeeID
if ##rowcount = 0 -- manager not found?
return 1;
END
And you call it this way:
DECLARE #return_status int;
DECLARE #managerID int;
EXEC #return_status = GetImmediateManager 2, #managerID output;
if #return_status = 1
print N'Immediate manager not found!';
else
print N'ManagerID is ' + #managerID;
go
You should use the return value for status codes only. To return data, you should use output parameters.
If you want to return a dataset, then use an output parameter of type cursor.
more on RETURN statement
Use this code, Working properly
CREATE PROCEDURE [dbo].[sp_delete_item]
#ItemId int = 0
#status bit OUT
AS
Begin
DECLARE #cnt int;
DECLARE #status int =0;
SET NOCOUNT OFF
SELECT #cnt =COUNT(Id) from ItemTransaction where ItemId = #ItemId
if(#cnt = 1)
Begin
return #status;
End
else
Begin
SET #status =1;
return #status;
End
END
Execute SP
DECLARE #statuss bit;
EXECUTE [dbo].[sp_delete_item] 6, #statuss output;
PRINT #statuss;
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare #anID int
exec #anID = dbo.StoredProc_Fetch #ID, #anotherID, #finalID
exec dbo.ADifferentStoredProc #anID (no value here)
To this:
declare #t table(id int)
declare #anID int
insert into #t exec dbo.StoredProc_Fetch #ID, #anotherID, #finalID
set #anID= (select Top 1 * from #t)