'Simple ISEMPTY() function in SQL Server throws a non-boolean type error
I'm trying to write a simple ISEMPTY function in Microsoft SQL Server:
DROP FUNCTION IF EXISTS ISEMPTY;
GO
CREATE FUNCTION ISEMPTY
(@charsequence nvarchar(max))
RETURNS BIT
AS
BEGIN
DECLARE @result BIT;
IF (@charsequence IS NULL OR LEN(@charsequence) = 0)
SET @result = 1
ELSE
SET @result = 0;
RETURN @result;
END
GO
When I want to test it with:
SELECT CASE WHEN dbo.ISEMPTY('') THEN 'REACHED!' END;
I get the following error:
[S0001][4145] Line 1: An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.
What goes wrong here?
Solution 1:[1]
The function returns a number so you need a comparison with a number to get a boolean value
CREATE FUNCTION ISEMPTY( @charsequence nvarchar(max)) returns BIT AS begin DECLARE @result BIT; IF (@charsequence IS NULL OR LEN(@charsequence) = 0 ) SET @result = 1; ELSE SET @result = 0; RETURN @result; end
GO
SELECT CASE WHEN dbo.ISEMPTY('') = 1 THEN 'REACHED!' END; GO| (No column name) | | :--------------- | | REACHED! |
db<>fiddle here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
