Sql Server Stored procedure returns -1 - sql-server

I am writing code on entity framework 6.0, linq on asp.net, sql server platform.
I've written a stored procedure which supposed to return an output value (0 or 1)
Firstly I wrote SP by using output parameter as follows:
ALTER proc [dbo].[checkUser]
(
#oNo int,
#pw varchar(50),
#val int output
)
as
begin
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
set #val=1
end
if not exists(select * from Users where #oNo=sNo and #pw=password)
begin
set #val=0
end
end
Didnt work. It returned -1. Then I changed SP like this:
ALTER proc [dbo].[checkUser]
(
#oNo int,
#pw varchar(50)
)
as
begin
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
return 1
end
else
begin
return 0
end
end
Each ways stored procedure returns only -1
Can you help me please, where am i doing wrong?

Try to replace "return" by "select".
if EXISTS (select * from Users where #oNo=sNo and #pw=password)
begin
select 1
end
else
begin
select 0
end

Related

IF statement using output of SPROC SQL [duplicate]

This question already has answers here:
TSQL: Call a stored procedure from another stored procedure and read the result
(5 answers)
Closed 4 years ago.
I am creating stored procedures (sprocs) to perform operations on my tables in my database. I have a sproc SubjectExists that returns '1' if the subject name entered is in the subject table and returns '0' if it does not exist.
CREATE PROCEDURE SubjectExists #SubjName varhcar(20)
AS
SELECT CASE WHEN EXISTS(
SELECT *
FROM Subject
WHERE Subject_Name = #SubjName
)
THEN CAST (1 AS BIT)
ELSE CAST (0 AS BIT)
END
I am now making another sproc that deletes a subject from the table. I want to make this sproc such that it uses SubjectExists and if the output of it is a 1 (i.e. the subject does exist) then it deletes the subject and if the output from SubjectExists is 0, it does nothing.
How would I go about doing this?
I have tried experimenting with the below but no luck so far.
CREATE PROCEDURE DeleteSubject #SubjName varchar(20)
AS
IF (EXEC StudentExists Bob)
DELETE FROM Subject
WHERE Subject_Name = #SubjName;
Can anyone please guide me as to how I would do this.
Thanks
At first, your stored procedure should return value:
CREATE PROCEDURE SubjectExists #SubjName varchar(20)
AS
BEGIN
DECLARE #ReturnValue int
SELECT #ReturnValue = CASE WHEN EXISTS(
SELECT *
FROM Subject
WHERE Subject_Name = #SubjName
)
THEN CAST (1 AS BIT)
ELSE CAST (0 AS BIT)
END
RETURN #ReturnValue
END
Then you can declare some table to store results of your stored procedure and if it is eligible, then run your code
DECLARE #FooValue int;
EXEC #FooValue = SubjectExists 'helloWorld!:)'
IF #FooValue = 1
BEGIN
DELETE FROM Subject
WHERE Subject_Name = #SubjName;
END
You need to get the return value from the stored procedure like this-
DECLARE #returnvalue INT
EXEC #returnvalue = StudentExists Bob
and then you can make your If condition.

What is the default return type of store procedure give with example?

The following Stored Procedure accepts EmployeeId as a parameter. It checks whether an Employee with the supplied EmployeeId exists in the Employees table of the Northwind database.
What will be the default return type and value?
CREATE PROCEDURE CheckEmployeeId
#EmployeeId INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Exists INT
IF EXISTS(SELECT EmployeeId
FROM Employees
WHERE EmployeeId = #EmployeeId)
BEGIN
SET #Exists = 1
END
ELSE
BEGIN
SET #Exists = 0
END
RETURN #Exists
END
Whenever, you execute a procedure, it returns an integer status variable.Usually,zero indicates success and non-zero indicates failure.
Now. its depends on you, what integer value you want to return from procedure to inform your application.
A procedure can return an integer value called a return code to indicate the execution status of a procedure. You specify the return code for a procedure using the RETURN statement.
Suppose you have
Return code value Meaning
0 Employee does not exists.
1 Employee exists.
Example:-
CREATE PROCEDURE CheckEmployeeId
#EmployeeId INT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT EmployeeId
FROM Employees
WHERE EmployeeId = #EmployeeId)
BEGIN
RETURN(1)
END
ELSE
BEGIN
RETURN(0)
END
RETURN(0)
END
RETURN always returns int from a stored procedure.
The default value can vary if
- try to return NULL (get zero and a warning)
- you get a SQL Server error where you get a value "10 minus the severity level of the error"
But it's always int

SQL Server: how to generate serial number by dynamic SQL

create procedure test
(#TABLE_NAME varchar(20))
as
declare #lastval varchar(10)
set #lastval = right('000000000' + convert(varchar(10),
(select IsNull(max(Serialno), 0) + 1
from #TABLE_NAME)), 10)
return #lastval
end
Now tell me how I could compose or form dynamic SQL with above SQL where I will pass table name to store procedure when call that stored procedure?
How to return #lastval value to its calling environment?
How to call stored procedure test from another stored procedure where I will store the return value ?
Guide me with sample code.
Genearlly, it's best to use an IDENTITY or a SEQUENCE to assign serial numbers. A zero-padded string or other formatting requirements could be added to the table as a computed column based on the underlying serial integer or formatted in the app code. However, both IDENTITY and SEQUENCE may have gaps, such as due to rollbacks or SQL Server service restart.
In cases where an unbroken sequence of serial values is required by business, one can maintan the last assigned values in a table and assign values transactionally. Below is an example that returns the value using an OUTPUT parameter. Although the proc in your question uses the stored proc RETURN value for this purpose, that should only be used to indicate success or failure, not return data.
CREATE TABLE dbo.TableSerialNumber(
TableName sysname NOT NULL
CONSTRAINT PK_SerialNumber PRIMARY KEY
, SerialNumber int NOT NULL
, FormatString nvarchar(20) NULL
);
GO
INSERT INTO dbo.TableSerialNumber VALUES('Invoice', 0, '0000000000');
INSERT INTO dbo.TableSerialNumber VALUES('PurchaseOrder', 0, '0000000000');
GO
CREATE PROC dbo.GetNextSerialNumberForTable
#TableName sysname
, #FormattedSerialNumber varchar(10) OUTPUT
AS
SET NOCOUNT ON;
DECLARE
#SerialNumber int
, #FormatString nvarchar(20);
UPDATE dbo.TableSerialNumber
SET
#SerialNumber = SerialNumber += 1
, #FormatString = FormatString
WHERE TableName = #TableName;
IF ##ROWCOUNT = 0
RAISERROR('Table %s does not exist in dbo.TableSerialNumber', 16, 1, #TableName);
SET #FormattedSerialNumber = CAST(FORMAT(#SerialNumber, #FormatString) AS varchar(10));
GO
--example usage
CREATE PROC dbo.InsertInvoice
#InvoiceData int
AS
SET XACT_ABORT ON;
DECLARE #InvoiceNumber varchar(10);
BEGIN TRY
BEGIN TRAN;
EXECUTE dbo.GetNextSerialNumberForTable
#TableName = N'Invoice'
, #FormattedSerialNumber = #InvoiceNumber OUTPUT;
INSERT INTO dbo.Invoice (InvoiceID, InvoiceData)
VALUES(#InvoiceNumber, #InvoiceData);
SELECT #InvoiceNumber AS InvoiceNumber;
COMMIT;
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
GO

Why does the output of this simple proc change datatypes?

In testing output values from procs, why does the final select #TestValOut return 0 instead of null or an empty string?
I understand the correct way to do this is by using OUTPUT parameters, so the question really becomes: Why is the datatype of the set value of #TestValOut, at execution, an integer?
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'Custom.test') AND type in (N'P', N'PC'))
DROP PROCEDURE Custom.test
GO
CREATE PROCEDURE Custom.test (
#CurrentUserID INT = 1
)
As
Declare #TestValIn varchar(max)
select #TestValIn='asdf'
GO
BEGIN TRAN
Declare #TestValOut varchar(max)
set #TestValOut='ffff'
Exec #TestValOut=Custom.test #CurrentUserID=1
select #TestValOut
ROLLBACK
A return value in a stored procedure is always an integer, as a matter of fact you can only use an integer with a return value. The fact that you see 0 means the proc executed correctly, this is the return value that SQL Server returns telling you what the result of the proc execution is
For fun do a select 1/0 in the proc and you will see it won't be 0 anymore
See here
Is a return value of 0 always a success in stored procedures?
here are the examples from that answer
CREATE PROC pr_test AS
SELECT 1/0
RETURN 0
GO
Now run it
DECLARE #i INT
exec #i = pr_test
SELECT #i -- will be 0
DROP PROC pr_test
Now let's do it again without the return statement
CREATE PROC pr_test2 AS
SELECT 1/0
GO
DECLARE #i INT
exec #i = pr_test2
SELECT #i -- will be - 6
Better to use an output parameter to pass back statuses and or messages
I think what you're trying to do is use an output parameter, which should be done like this.
CREATE PROCEDURE Custom.test (
#CurrentUserID INT = 1,
#TestValOut varchar(max) OUTPUT
)
As
select #TestValOut='asdf'
GO
BEGIN TRAN
Declare #TestValOut varchar(max)
Exec Custom.test #CurrentUserID=1, #TestValOut OUTPUT
select #TestValOut
ROLLBACK
#TestValOut is assigned the value that would be returned by an "RETURN" like this:
CREATE PROCEDURE Custom.test (
#CurrentUserID INT = 1
)
As
Declare #TestValIn varchar(max)
select #TestValIn='asdf'
RETURN --defaults to zero, this is the value
GO
or
CREATE PROCEDURE Custom.test (
#CurrentUserID INT = 1
)
As
Declare #TestValIn varchar(max)
select #TestValIn='asdf'
RETURN 0 --this is the value
GO
Your stored procedure doesn't actually do anything at all: there is no resultset. To see the difference...
CREATE PROCEDURE Custom.test (
#CurrentUserID INT = 1
)
As
select * from sys.objects
RETURN 42 --random value
GO
DECLARE #rtn int
EXEC #rtn = Custom.test
--you have the output of sys.objects now
--and the scalar RETURN value
SELECT #rtn
You need to explicity say what value to return. Default is 0
CREATE PROCEDURE Custom.test (
#CurrentUserID INT = 1
)
As
Declare #TestValIn varchar(max)
select #TestValIn='asdf'
RETURN 0
GO

Help with an IF in SQL SERVER Stored procedure

can anyone help me with construction of an IF in a stored procedure in sql server.
Basically I have a simple stored procedure but I now need to pass in a new input parameter which depending if it is true I pass the value D and if its false I pass the value A. But the change is in the middle of a subquery.. let me explain... here is the stored procedure. basically if I send in True for ReturnOldStatus I execute the subquery ItemStatus='D' and if it is false then i pass in ItemStatus='A'
CREATE PROCEDURE [dbo].[MyTempStoredProc]
(
#IdOffice Int,
#ReturnOldStatus bit
)
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM Offices
WHERE
IdOffice = #IdOffice
AND (V.OffType NOT IN (
SELECT * FROM MiscOff
WHERE
ItemStatus= 'D') // This needs to be ItemStatus ='A' if FALSE is passed in on the input param
Any ideas??
Thanks
I would solve it like this:
declare #itemStatus varchar(1);
if (#inputParam = 'FALSE')
begin
set #itemStatus = 'A'
end
else
set #itemStatus = 'D'
SELECT * FROM Offices
WHERE
IdOffice = #IdOffice
AND (V.OffType NOT IN (
SELECT * FROM MiscOff
WHERE ItemStatus= #itemStatus)
)
T-Sql is not my native language, so there may be errors in there...
Just use the T-SQL if statement:
IF #ReturnOldStatus = 0
BEGIN
--Some statements
END
ELSE
BEGIN
--Some other statements
END
I think this will suffice for your problem. If not, look into the DECLARE/SET statements in TSQL.
CREATE PROCEDURE [dbo].[MyTempStoredProc]
(#IdOffice Int,
#ReturnOldStatus bit )
AS BEGIN
SET NOCOUNT ON;
SELECT * FROM Offices
WHERE IdOffice = #IdOffice
AND (V.OffType NOT IN (SELECT * FROM MiscOff
WHERE (ItemStatus= 'D' AND #ReturnOldStatus = 1)
OR
(ItemStatus= 'A' AND #ReturnOldStatus = 0)
)

Resources