The influence of N/A and NULL on SELECT...INTO statement in MySQL

I. Introduction

       Write a mysql function, the result of the function is wrong, and it is found that the error is caused by the failure to assign values ​​to the repeatedly used variables using SELECT...INTO.

Repeated use of a variable, the second variable assignment failed, still the value of the first assignment, the original is the second query result is N/A.

SELECT N/A INTO variable; - This assignment method will fail the assignment and will retain the last value.

Two, test

1. Create a test data table

CREATE TABLE test ( id INT auto_increment, num INT, PRIMARY KEY ( id ) );

2. Insert data

INSERT INTO `demo`.`test`(`id`, `num`) VALUES (2, NULL);
INSERT INTO `demo`.`test`(`id`, `num`) VALUES (3, 3);

3. Test

(1) Scenario 1: There is no such data in the database

set @a = 100;

SELECT num from test where id = '1' into @a;

-- SELECT num from test where id = '2' into @a;

-- SELECT num from test where id = '3' into @a;

SELECT @a;

Results: 100

(2) Scenario 2: This piece of data exists in the database, but the data is null

set @a = 100;

-- SELECT num from test where id = '1' into @a;

SELECT num from test where id = '2' into @a;

-- SELECT num from test where id = '3' into @a;

SELECT @a;

Result: Null

(3) Scenario 3: There is entry data in the database, and the value is 3

set @a = 100;

-- SELECT num from test where id = '1' into @a;

-- SELECT num from test where id = '2' into @a;

SELECT num from test where id = '3' into @a;

SELECT @a;

Result: 3

Guess you like

Origin blog.csdn.net/cs373616511/article/details/107318142