In SQL we can use the "WHERE 1=1 hack" to easily generate a WHERE statement in a loop, so we don't need to check if the current iteration is the first one.
without WHERE 1 :
//I haven't tried the C++ code below, it's just an example to briefly explain the "hack"
string statement = "WHERE";
for (int i = 0 ; i < list.size() ; i++)
{
if (i != 0)
{
statement += " AND "; //we don't want to generate "WHERE AND"
}
statement += list[i];
}
the generated statement :
WHERE <something_1>
AND <something_2>
AND <something_3>
with WHERE 1 :
string statement = "WHERE 1 = 1"; // Added "1 = 1"
for (int i = 0 ; i < list.size() ; i++)
{
statement += "AND" + list[i];
}
the generated statement :
WHERE 1 = 1
AND <something_1>
AND <something_2>
AND <something_3>
My issue : I need to generate an "ORDER BY" statement, and I was wondering if such a hack also exists for the ORDER BY statement. I could check if the current iteration in the loop is the last one, but there's maybe a better solution.
ORDER BY a DESC,
b DESC,
c DESC,
d DESC,
<dummy statement added at the end, so I don't need to remove the last comma>
From what I've read I cannot use "ORDER BY 1", so does a similar hack actually exists?