Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a Boolean parameter in SQL statement?

Tags:

sql

sql-server

How can I declare a Boolean parameter in SQL statement?

like image 360
Sergio Tapia Avatar asked Aug 31 '09 00:08

Sergio Tapia


People also ask

How do you set a boolean value in SQL query?

Sql server does not expose a boolean data type which can be used in queries. Instead, it has a bit data type where the possible values are 0 or 1 . So to answer your question, you should use 1 to indicate a true value, 0 to indicate a false value, or null to indicate an unknown value.

How do you declare a parameter in SQL query?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

Is there a Boolean data type in SQL?

There is boolean data type in SQL Server. Its values can be TRUE , FALSE or UNKNOWN . However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. = , <> , < , >= ) or logical operators (e.g. AND , OR , IN , EXISTS ).


2 Answers

The same way you declare any other variable, just use the bit type:

DECLARE @MyVar bit
Set @MyVar = 1  /* True */
Set @MyVar = 0  /* False */

SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar

Note this is semantically different from a true boolean. The 1/0 values won't always just map to true/false the way you might expect.

like image 100
Joel Coehoorn Avatar answered Oct 02 '22 15:10

Joel Coehoorn


SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

like image 37
Eric Avatar answered Oct 02 '22 16:10

Eric