I'm trying to write a T-SQL function that evaluates to a boolean.
I've read several articles stating that BIT is T-SQL equivalent of a BOOLEAN type (such as Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?, http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/c3143a77-c921-40a7-920e-3d5c5f7a269a).
Yet, when I create function returning BIT:
create function dbo.fn_checkLength( @name nvarchar(50), @maxLength int) returns bit
as begin
if len(@name) > @maxLength return cast(0 as bit);
return cast(1 as bit);
end;
GO
It does not behave as a function that evaluates to a boolean, because the following statement:
create table dbo.test_table (
id int,
name nvarchar(50),
constraint
ck_test_table_maxLength
check (
dbo.fn_checkLength(name, 10)
)
);
GO
Gives me:
Msg 4145, Level 15, State 1, Line 10
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
To make it work, when calling my function I have add a boolean operator in the mix, to really make the expression boolean:
create table dbo.test_table (
id int,
name nvarchar(50),
constraint
ck_test_table_maxLength
check (
dbo.fn_checkLength(name, 10) > 0
)
);
GO
Why is this so? Is there any way to declare function that can be used in T-SQL statement as a regular boolean expression?
Thanks!