我想写这样的代码:
select col1,col2,col3,col4
from x
where ----
order by all
更多细节:我使用Sp_executesql
从数据库动态获取我的列以执行我的SQL语句,我不知道返回列的数量是多少,我想通过所有这些动态列对这些列进行排序
这是我的代码:
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
清楚?
由于
答案 0 :(得分:0)
我仍然不知道,如果我明白你在问什么或不知道。如果要按列的顺序排序行,即先按第一列,然后按第二列,依此类推,那么haytem在一小时前就在评论部分给出了答案:完全构建ORDER BY子句与构建SELECT子句的方式相同。
SET @SelectStmt = 'SELECT * FROM ( SELECT Distinct' + isnull(@SelectColumns ,'-1')
+ ' FROM ' + @tbl_name
+ ' WHERE det.frd_id =''' + @frd_id_BU + ''' ' + @and_cond +') A'
+ ' ORDER BY ' + isnull(@SelectColumns ,'1')
如果@SelectColumns中没有列,则选择-1并按1排序,即第一列和唯一列。