我有一个在动态SQL语句中使用的查询。在这种情况下,它会获取所选字段,其订单和排序首选项的列表,以便创建SORT
语句。
-- Insert the data into the sort statements
INSERT into @sortStatements (sortStatement)
SELECT fo.fieldName + ' ' + b.FilterValues
FROM red.dbo.BS_ContentRequests_Tasks_User_Fields AS a
JOIN red.dbo.BS_ContentRequests_Tasks_Fields_Options AS fo
ON a.fieldID = fo.fieldID
JOIN (
Select Main.fieldID, Left(Main.FilterValues,Len(Main.FilterValues)-1) As "FilterValues"
From
(
Select distinct ST2.fieldID,
(
Select ISNULL(ST1.[sortType], 'ASC') + ', ' AS [text()]
From red.dbo.BS_ContentRequests_Tasks_User_Fields ST1
JOIN dbo.BS_ContentRequests_Tasks_Fields_Options AS fl
ON st1.fieldID = fl.fieldID
Where ST1.fieldID = ST2.fieldID
AND ST1.QID = @QID
ORDER BY ST1.sortOrder ASC
For XML PATH ('')
) [FilterValues]
From red.dbo.BS_ContentRequests_Tasks_User_Fields ST2
WHERE ST2.QID = @QID
) [Main]
) as b
ON a.fieldID = b.fieldID
WHERE a.QID = @QID
SELECT * FROM @sortStatements
-- Trim off the trailing comma
SELECT @sortClause = coalesce(@sortClause + ', ', '') + sortStatement
FROM @sortStatements
-- Set a variable to hold the whole WHERE logic which we will append later
SET @sort = (SELECT @sortClause)
SELECT @sort
sortStatements
的结果集如下:
我在代码中使用的最后一个字符串(@sort
的结果)是:
requestContentType ASC, dateRequested ASC, desiredCompletion ASC, dueDate ASC, requestID DESC, requestTitle ASC, requestType DESC, startDate ASC, requestStatus ASC, taskName ASC, requestorName ASC, requestorNTID ASC, taskStatus ASC, taskID ASC
这里的问题是那些字段名称的顺序不正确。在中间语句中,我有我的order by子句,应该按sortOrder
这是fieldName及其排序值,它的顺序应为:
正如您所看到的,最终输出没有特定的顺序..这个查询的一部分导致某些类型的排序覆盖了我自己的排序吗?我尝试将order by clause
放在几个区域,但它不会改变最终输出。
思想?
答案 0 :(得分:2)
将sortOrder添加到@sortStatements的生成中,然后
SELECT @sortClause = coalesce(@sortClause + ', ', '') + sortStatement
FROM @sortStatements
Order by sortOrder