We wish to specify the sorting columns dynamically i.e. through a variable.
The names of the column that we wish to sort by are specified as strings in an environment variable.
One Column
BEGIN
DECLARE v_columns STRING;
SET v_columns = 'col_1';
EXECUTE IMMEDIATE FORMAT("""SELECT *
FROM refcon.dataset.table_1
ORDER BY %s
""", v_columns);
END;
Here is how this works:
v_columns
variable.EXECUTE IMMEDIATE
to execute our dynamic query using the v_columns
variable.FORMAT
function which formats a data type expression as a string. %s
will be replaced
with the v_columns
value.FORMAT
will be SELECT * FROM refcon.dataset.table_1 ORDER BY col_1
.Multiple Columns
BEGIN
DECLARE v_columns STRING;
SET v_columns = 'col_1, col_2 DESC';
EXECUTE IMMEDIATE FORMAT("""SELECT *
FROM refcon.dataset.table_1
ORDER BY %s
""", v_columns);
END;
Here is how this works:
v_columns
variable.