Home > Database > Mysql Tutorial > body text

How to Successfully Cast INT to BIT in MySQL 5.1?

Linda Hamilton
Release: 2024-10-28 20:49:30
Original
507 people have browsed it

How to Successfully Cast INT to BIT in MySQL 5.1?

Casting INT to BIT in MySQL 5.1: An Impossible Task

In transitioning from SQL Server to MySQL 5.1, a challenge arises when attempting to create a table with a bit column using a select statement. The intuitive approach of casting an integer column to a bit, as seen in the following example, fails:

CREATE TABLE myNewTable AS
SELECT cast(myIntThatIsZeroOrOne as bit) AS myBit
FROM myOldtable
Copy after login

MySQL expresses disapproval at attempts to cast to bit, prompting the question: How can we instruct it to treat an integer column containing only 0s and 1s as a bit?

The Limitations of Casting

Unfortunately, there is no direct solution. CAST and CONVERT functions in MySQL 5.1 support casting only to specific data types, excluding BIT and related integer types.

Custom Function to the Rescue

Despite the limitation, it is possible to create a custom function to perform the casting. Here's how:

DELIMITER $$

CREATE FUNCTION cast_to_bit (N INT) RETURNS bit(1)
BEGIN
    RETURN N;
END
$$
Copy after login

Visual Verification

To confirm the functionality of the cast_to_bit function, a view can be created:

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)
Copy after login

Examining the view with DESCRIBE reveals that all values have been converted to bit(1).

The above is the detailed content of How to Successfully Cast INT to BIT in MySQL 5.1?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template