Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TSQL, how to evaluate an expression and assign it to a BIT field?

I'm struggling on something very simple. I'm trying to assign the results of a boolean expression to a BIT variable.

Basically I would like to do something like:

DECLARE @is_search_term_empty BIT  SET @is_search_term_empty = (@search_term = '') 

where @search_term is a NVARCHAR(128) declared somewhere else in the code.

I cannot work out the syntax to evaluate something and assign it to a BIT variable, ie:

SET @is_search_term_empty = (1 > 2)  

Thanks.

like image 981
Giuseppe Romagnuolo Avatar asked Feb 26 '11 12:02

Giuseppe Romagnuolo


People also ask

How do you assign a bit value in SQL?

To insert a new value to the BIT column, use INSERT statement: INSERT INTO table_name (bit_column) VALUES (1); You can also use TRUE and FALSE as the inputs for the BIT columns, SQL Server will automatically convert them as follow: TRUE will be converted to 1.

How do I cast a bit in SQL?

Data Type Conversions using the SQL CAST Function. For example, if we want to cast a Boolean value from the bit data type to a tiny int data type, we can do it with a valid expression such as: DECLARE @mybit BIT = 1; SELECT Test = CAST(@mybit AS TINYINT); Not every data type can be converted to all possible data types.

How do I update a bit field in SQL?

1 Answer. Show activity on this post. Bits in SQL Server are always stored as 1 or 0 in a bitmap. The "Edit Table" option in SSMS just translates this to True or False for presentation purposes, this is nothing to do with how it is actually stored.

What is bit value in SQL?

SQL Server BIT data type is an integer data type that can take a value of 0, 1, or NULL . The following illustrates the syntax of the BIT data type: BIT. SQL Server optimizes storage of BIT columns. If a table has 8 or fewer bit columns, SQL Server stores them as 1 byte.


1 Answers

You can do this with a CASE statement:

DECLARE @bitvar BIT  DECLARE @search_term varchar(128)  set @search_term = 'abc'  SET @bitvar = CASE                   WHEN (@search_term = 'abc') THEN 1                  ELSE 0               END  select @bitvar 
like image 55
Mitch Wheat Avatar answered Sep 22 '22 13:09

Mitch Wheat