Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a bit literal in a sql query

Tags:

sql

sql-server

I have a view which unions multiple tables. One table has a bit column called VisibleToCustomer. One of the other tables does not have this, and I want to hard code it in the view. I can do this with strings:-

SELECT  'Fred' "VisibleToCustomer", ....

or even ints

SELECT  1 "VisibleToCustomer", ....

but how do I do it with a bit? I.e. I want to do something like

SELECT  true "VisibleToCustomer", ....

but obviously the above doesn't work!

like image 415
Cookie Avatar asked Sep 06 '25 12:09

Cookie


1 Answers

You can use

 SELECT  'true' AS "VisibleToCustomer"

bit has higher data type precedence than varchar so this will cast correctly.

SELECT CAST(1 AS BIT) AS "VisibleToCustomer"
UNION ALL
SELECT 'false' 

Returns

+-------------------+
| VisibleToCustomer |
+-------------------+
|                 1 |
|                 0 |
+-------------------+
like image 62
Martin Smith Avatar answered Sep 08 '25 11:09

Martin Smith