I am transitioning from SQL Server to MySQL 5.1 and seem to be tripped up trying to create a table using a select statement so that the column is a bit.
Ideally the following would work:
CREATE TABLE myNewTable AS
SELECT cast(myIntThatIsZeroOrOne as bit) AS myBit
FROM myOldtable
However sql is very unhappy at casting as a bit. How can I tell it to select an int column (which I know only has 0s and 1s) as a bit?
To cast VARCHAR to INT, we can use the cast() function from MySQL. Here is the syntax of cast() function. For our example, we will create a table with the help of create command. Display all records with the help of select statement.
MySQL CAST() FunctionThe CAST() function converts a value (of any type) into the specified datatype.
TINYINT is a very small integer. The minimum and maximum SIGNED values are -128 and 127 respectively, while for UNSIGNED values TINYINT range is from 0 to 255. TINYINT uses 1 byte per row. It is the best option when you want to save space on your disk and enhance performance.
You cannot!
CAST and CONVERT only work to:
No room for: BIT, BITINT, TINYINT, MEDIUMINT, BIGINT, SMALLINT, ...
However, you can create your own function cast_to_bit(n):
DELIMITER $$
CREATE FUNCTION cast_to_bit (N INT) RETURNS bit(1)
BEGIN
RETURN N;
END
To try it yourself, you can create view with several conversions like:
CREATE VIEW view_bit AS
SELECT
cast_to_bit(0),
cast_to_bit(1),
cast_to_bit(FALSE),
cast_to_bit(TRUE),
cast_to_bit(b'0'),
cast_to_bit(b'1'),
cast_to_bit(2=3),
cast_to_bit(2=2)
... and then describe it!
DESCRIBE view_bit;
Ta-dah!! Everyone is bit(1) now!!!
Try using case:
CREATE TABLE myNewTable AS
SELECT (case myIntThatIsZeroOrOne when 1 then true else false end) AS myBit
FROM myOldtable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With