5

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!

0

2 Answers 2

9

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 |
+-------------------+
Sign up to request clarification or add additional context in comments.

1 Comment

Huge thanks for such a quick and comprehensive reply, works a treat!
4

The three possible values for bit literals: select cast(1 as bit), cast(0 as bit), cast(null as bit)

Note: Any non zero values will become 1 when cast to bit, CAST(-1.2e-33 AS BIT). I would recommend against writing a bit literal that way.

4 Comments

And CAST('true' AS BIT), CAST('false' AS BIT)
@MartinSmith, I did not know that. Thank you.
thanks for a quick reply, used Martins but yours was good also!
Also numeric string literals, as well as + and -, which are both zero: CAST('1' AS BIT), CAST('0000' AS BIT), CAST('-' AS BIT), CAST('+' AS BIT).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.