Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server sort by first column in table

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?

like image 593
Rod Avatar asked Dec 07 '22 11:12

Rod


1 Answers

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)

like image 127
Oded Avatar answered Jan 03 '23 02:01

Oded