Reputation: 41
I need help with this stored function:
.
CREATE PROCEDURE ( @id varchar(12), @subvarchar(12))
IF EXISTS(SELECT * FROM contacts WHERE id = @id AND subid = @subid )
.....//return true else ....//return false
I need to return true or false.
Upvotes: 1
Views: 4514
Reputation: 107277
TL;DR
I would use a function (scalar, or possibly table-valued but this would require a change to a set-based approach)
SqlFiddle of the various options here:
Details
There is no boolean type in SQL Server - the closest is a BIT (0 / 1). Stored procedures can only return an INT
, although it is unusual to (ab)use the return value in this way, as it is intended to indicate the success or failure of the procedure.
CREATE PROCEDURE dbo.MyProc( @key varchar(12), @subkey varchar(12)) AS
RETURN (
SELECT CASE
WHEN exists
(select * from contacts where [key]=@key and [subkey]=@subkey)
THEN 1
ELSE 0
END);
More commonly, you would use an OUTPUT
parameter:
CREATE PROCEDURE dbo.MyOutputParamProc( @key varchar(12), @subkey varchar(12), @result BIT OUTPUT) AS
SET @result =
CASE
WHEN exists
(select * from contacts where [key]=@key and [subkey]=@subkey)
THEN 1
ELSE 0
END;
GO
Alternatively, you could SELECT
a result, which would return a single row, single column.
CREATE PROCEDURE dbo.MyProc( @key varchar(12), @subkey varchar(12)) AS
SELECT CASE
WHEN exists
(select * from contacts where [key]=@key and [subkey]=@subkey)
THEN 'true'
ELSE 'false'
END AS 'Result';
That said, since you aren't changing data, a User Defined Function could be preferable to a PROC in this case, e.g.:
CREATE FUNCTION dbo.MyFunc(@key varchar(12), @subkey varchar(12))
RETURNS BIT
AS BEGIN
RETURN (SELECT CASE
WHEN exists(select * from contacts where [key]=@key and subkey=@subkey)
THEN 1
ELSE 0
END);
END;
Called like so:
SELECT dbo.MyFunc('key', 'subkey')
One last point - if you need to retrieve several keys at the same time, and if performance is important, then you might also need to consider approaching this problem in a set-based manner, e.g. by accepting a Table Valued Parameter to your proc / function.
Upvotes: 1