Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

casting - How can I cast an int to a bit in MySQL 5.1?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot!

CAST and CONVERT only work to:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

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!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...