简体   繁体   中英

Syntax error near “Order By” - 'Incorrect syntax near the keyword 'ORDER'.'

I have been staring at this for too long and I can't seem to see where I went wrong.

I have a stored procedure that has to return a bunch of data where the "ExtractedText" matches the word the person is searching for:

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 is a column in one of the tables, @FilterQuery is the word the user typed in that it is looking for. @SortName, is the name by wich it gets sorted.

Command examples: @FilterField = "ExtractedText", @FilterQuery="something", @SortName="EventID", @SortOrder="desc"

This is the error:

Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'ORDER'.

Full command:

WHERE ExtractedText LIKE '%add%' ORDER BY EventID desc;

You cannot order by variable. You need to use dynamic 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

Look in this post:

Can I store SQL Server sort order in a variable?

它不起作用的原因是因为我错过了WHERE EventID = convert(nvarcahr,@EventID)并且刚刚取出了“DISTINCT”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM