Bootstrap

使用case,when查询数据的性别

DELIMITER //
CREATE PROCEDURE InsertStudent(
    IN p_userName VARCHAR(255),
    IN p_age INT,
    IN p_introduce TEXT
)
BEGIN
    -- 检查输入参数不为空
    IF p_userName IS NULL OR p_age IS NULL OR p_introduce IS NULL THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Input values must not be null';
    END IF;

    -- 检查userName不以张、王、李、兆开头
    IF LEFT(p_userName, 1) = '张' OR LEFT(p_userName, 1) = '王'
        OR LEFT(p_userName, 1) = '李' OR LEFT(p_userName, 1) = '兆' THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'UserName must not start with Zhang, Wang, Li, or Zhao';
    END IF;

    -- 生成随机电话号码
    DECLARE randomPhone VARCHAR(20);
    SET randomPhone = LPAD(FLOOR(RAND() * 10000000000), 11, '0');

    -- 生成随机性别
    DECLARE randomSex ENUM('M', 'F', 'O');
    SET randomSex = ELT(1 + FLOOR(RAND() * 3), 'M', 'F', 'O');

    -- 生成随机创建日期
    DECLARE randomCreateDate DATE;
    SET randomCreateDate = CURDATE() - INTERVAL FLOOR(RAND() * 365) DAY; -- 随机过去的一年内日期

    -- 插入数据
    INSERT INTO student (createDate, userName, phone, age, sex, introduce)
    VALUES (randomCreateDate, p_userName, randomPhone, p_age, randomSex, p_introduce);
END //
DELIMITER ;




CALL InsertStudent('YourUserName', 25, 'This is an introduction.');
SELECT 
    id,
    userName,
    sex,
    CASE 
        WHEN sex = 'M' THEN '男性'
        WHEN sex = 'F' THEN '女性'
        WHEN sex = 'O' THEN '泰国人'
        ELSE '未知' -- 可选,为了处理未来可能出现的其他情况
    END AS sex_description
FROM 
    student
LIMIT 
    2000;

;