Câu hỏi phỏng vấn MySQL
Câu hỏi

What are REPEAT , LOOP and WHILE statements used for?

Câu trả lời

In MySQL, the REPEAT, LOOP, and WHILE statements are used for controlling the flow of execution by repeating a block of code under specific conditions. Each of these looping constructs serves a different purpose and is chosen based on the requirements of the task at hand.

REPEAT Statement

The REPEAT statement is used to execute a block of code repeatedly until a specified condition becomes true. It is particularly useful when the number of iterations is not known in advance but is determined by a condition evaluated at the end of each loop iteration. The syntax for the REPEAT statement includes a REPEAT keyword followed by the block of code to execute, an UNTIL keyword with a condition, and an END REPEAT clause[2][5][18].

For example, a REPEAT loop might be used to increment a value until it reaches a certain threshold:

sql Copy
REPEAT
    SET @value = @value + 1;
UNTIL @value > 100
END REPEAT;

This loop will continue to increment @value until it exceeds 100.

LOOP Statement

The LOOP statement provides the simplest form of iteration in MySQL, executing an indefinite loop that continues until it is explicitly terminated by a LEAVE statement. This type of loop is useful when an indefinite number of iterations are required, and the loop needs to be exited under specific conditions[8][12][16].

An example of a LOOP statement might look like this:

sql Copy
label1: LOOP
    IF @x > 10 THEN
        LEAVE label1;
    END IF;
    SET @x = @x + 1;
END LOOP label1;

In this example, the LOOP will continue to execute until @x is greater than 10.

WHILE Statement

The WHILE statement is used to execute a block of code repeatedly as long as a specified condition remains true. It is known as a pre-test loop because the condition is tested before each iteration, meaning the loop may not execute at all if the condition is false at the beginning[7][9][10][13].

Here’s an example of a WHILE loop:

sql Copy
WHILE @a < 10 DO
    SET @a = @a + 1;
END WHILE;

This...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

How can VIEW be used to provide security layer for your app?

middle

What are key constraints. What different types of constraints are there in MySQL?

middle

What is MySQL Workbench?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào