“Order By”附近的语法错误

时间:2012-10-25 20:17:12

标签: sql tsql stored-procedures

我一直盯着这看太久了,我似乎无法看到我哪里出错了 我有一个存储过程,必须返回一堆数据,其中“ExtractedText”匹配该人正在搜索的单词

Select @Command = 'select DISTINCT CaseFileEvents.InvestigatorID,convert(nvarchar,EventDate,111) as ''EventDate'',EventTime,EventDesc,TaskID,Privileged,Private,Email,HasAttachments,FName,LName, FName + '' '' + LName as Name ,CaseFileEvents.FileID,CaseFiles.FileName,ItemEntryGradeID, EventDescPlainText
                from CaseFileEvents
                join ......

                WHERE '+ @FilterField +' LIKE ''%' + @FilterQuery + '%'' ORDER BY ' + @SortName + ' ' + @SortOrder + ''; this area seems to bug out

@FilterField是其中一个表中的一列,@ FilterQuery是用户输入的单词,它正在寻找。 @SortName,是它被排序的名称。

EDIT-命令示例:@FilterField =“ExtractedText”,@ FilterQuery =“something”,@ SortName =“EventID”,@ SortOrder =“desc”

这是错误:Msg 156, Level 15, State 1, Line 10 Incorrect syntax near the keyword 'ORDER'.

完整命令:WHERE ExtractedText LIKE '%add%' ORDER BY EventID desc;

2 个答案:

答案 0 :(得分:1)

您无法按变量排序。您需要使用动态sql:

SELECT
     *
FROM
     My_Table
WHERE
     Whatever = @something
ORDER BY
     CASE @sort_order
          WHEN 'ASC' THEN
               CASE @order_by
                    WHEN 'surname' THEN surname
                    WHEN 'forename' THEN forename
                    WHEN 'fullname' THEN fullname
                    ELSE surname
               END
          ELSE '1'
     END ASC,
     CASE @sort_order
          WHEN 'DESC' THEN
               CASE @order_by
                    WHEN 'surname' THEN surname
                    WHEN 'forename' THEN forename
                    WHEN 'fullname' THEN fullname
                    ELSE surname
               END
          ELSE '1'
     END DESC

看看这篇文章:

Can I store SQL Server sort order in a variable?

答案 1 :(得分:0)

它不起作用的原因是因为我失踪了 WHERE EventID = convert(nvarcahr,@EventID) 然后拿出“DISTINCT”