I want to write like this code:
select col1,col2,col3,col4
from x
where ----
order by all
More details: I get my columns dynamically from database using Sp_executesql
to execute my SQL statement and I don't know what the number of returned columns is, and I want to sort these columns by all these dynamically columns.
This is my code:
ALTER PROCEDURE [dbo].[SP_Get_Trx_Log_details]
-- Add the parameters for the stored procedure here
@thread_id INT,
@frd_id_BU VARCHAR(max),
@and_cond VARCHAR(max)
AS
BEGIN
DECLARE @tbl_name NVARCHAR(300)
DECLARE @type NVARCHAR(10)
SELECT @type = Upper(thread_type)
FROM dbo.tbl_frd_threads
WHERE thread_id = @thread_id
IF( ( @type = 'M'
OR @type = 'Q'
OR @thread_id = 50 )
AND @thread_id <> 49 )
BEGIN
SET @tbl_name = 'dbo.tbl_frd_details_member_qa det LEFT JOIN dbo.tbl_frd_actions act ON det.frd_det_id = act.frd_id AND det.thread_id = act.thread_id AND act.action_type = ''C'' '
END
ELSE IF ( ( @type = 'P'
OR @thread_id = 49 )
AND @thread_id <> 50 )
BEGIN
SET @tbl_name = 'dbo.tbl_frd_details_provider det LEFT JOIN dbo.tbl_frd_actions act ON det.frd_det_id = act.frd_id AND det.thread_id = act.thread_id AND act.action_type = ''C'' '
END
IF ( @thread_id = 1000 ) -- JOIN details tbl with action tbl
BEGIN
SET @tbl_name = 'dbo.tbl_frd_details_member_qa det LEFT JOIN dbo.tbl_frd_actions act ON det.frd_det_id = act.frd_id AND det.thread_id = act.thread_id AND det.action_type = act.actions AND act.action_type = ''C'' '-- AND convert(datetime,act.action_date) = '''+Convert(varchar(50),@action_date)+''''
END
DECLARE @SelectStmt AS NVARCHAR(max)
DECLARE @SelectColumns AS NVARCHAR(max)
SELECT @SelectColumns = trx_log_cols
FROM tbl_frd_threads
WHERE thread_id = @thread_id
AND Isnull(trx_log_cols, '-1') != '-1'
AND trx_log_cols != ''
SET @SelectStmt = 'SELECT * FROM ( SELECT Distinct' + isnull(@SelectColumns ,'-1')+ ' FROM '
+ @tbl_name + ' WHERE det.frd_id ='''
+ @frd_id_BU + ''' ' + @and_cond +') A'
+ ' ORDER BY A.[Action Date] , 2,3,5,7'
-- Here I don't know the number of returned columns BUT I need to sort the returned columns by all columns or by odded number
EXEC Sp_executesql @SelectStmt
END
Clear ?
Thanks