If Else If Else - How Can It Work in Delphi? [Closed]
How Does This Piece of Code Work? If Name '' Then Begin Sql_1 End Else If Parametric Then Begin Sql2 End Else Begin Sql3 End End; Execute Sql Choosed by If or...
How does this piece of code work?
if name <> '' then
begin
sql_1
end
else if PARAMETRIC then
begin
sql2
end
else
begin
sql3
end
end;
execute sql choosed by if or elseif or else.....
name = is a string
PARAMETRIC = is a boolean
sql1, sql2, sql3 are different queries (sorry for forgot it :( )
2 Answers
In short:
- If
nameis not empty, onlysql_1will be executed - If
nameis empty andPARAMETRICistrue, onlysql_2will be executed - If
nameis empty andPARAMETRICisfalse, onlysql_3will be executed
You can always add begin/end statements to make it look more obvious.
if name <> '' then
begin
sql_1
end
else
begin
if PARAMETRIC then
begin
sql2
end
else
begin
sql3
end;
end;
end;
You say (in comments) you know C#. Well, in Delphi it works exactly the same. You can write if .. else statements, and add an extra condition after the else.
In Delphi:
if condition1 then
begin // Open multi-line statement.
Do1a;
Do1b;
end
else if condition2 then
Do2;
In C#:
if (condition1)
{ // Open multi-line statement.
Do1a;
Do1b;
}
else if (condition2)
Do2;
So, while I don't really understand the confusion, the answer to your question is: No, they don't get all executed. If condition1 is true, the 'elses' won't be executed. If condition1 is false and condition2 is true, the second statement (do2) is executed. If both are false, nothing is executed (or in your case, the conditionless else is executed, so you get SQL3).