exec ('select * from variable_table_name
order by @variable')
I'm trying to put together a dynamic sql statment where you specify a table name and sort column. It would be nice if I can just specify a table name to make the sql work.
Is there a way to choose the first column of a table to sort by if @variable sort by not specified?
You can use:
ORDER BY 1;
From ORDER BY Clause (Transact-SQL):
order_by_expression - Specifies a column or expression on which to sort the query result set. A sort column can be specified as a name or column alias, or a nonnegative integer representing the position of the column in the select list.
(emphasis mine)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With