Teeko
Teeko

Reputation: 53

How can I evaluate a boolean expression string in a SQL Server stored procedure?

I have a string with the following value:

COND_STRING = '(TRUE AND FALSE AND TRUE) OR FALSE'

How can I evaluate the outcome if it is True or False (1 or 0) in a SQL Server stored procedure?

Upvotes: 1

Views: 934

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270081

Hmmm . . . This is tricky, given that SQL Server doesn't support booleans. You can do:

declare @new_cond = replace(replace(@cond_string, 'TRUE', '(1=1)'), 'FALSE', '(1=0)');

declare @sql = 'select @result = (case when @cond then 1 else 0 end)';
set @sql = replace(@sql, '@cond', @new_cond);

declare @result int;

exec sp_executesql @sql, N'@result int output', @result=@result output;

Upvotes: 1

Squirrel
Squirrel

Reputation: 24763

i can only think of this way. Using Dynamic SQL

declare @str varchar(100) = '(TRUE AND FALSE AND TRUE) OR FALSE'

select  @str = replace(replace(replace(replace(@str, 'TRUE', '1'), 'FALSE', 0), 'AND', '&'), 'OR', '|')

select  @str    = 'SELECT' + @str

print   @str
exec    (@str)

Upvotes: 2

Related Questions