I keep encountering a syntax error when trying to ORDER BY on a section of dynamic SQL.
I have fairly basic knowledge of SQL but here's what I've tried (I don't want to include entire code), I have correctly declared SQL and DBName at the top, as well as using EXEC at the bottom:
SET @SQL = N'SELECT TOP 1
Test_Time,
Test_ID,
FROM ' + QUOTENAME(@DBName) + '.dbo.Event_Table'
ORDER BY Test_Time DESC
I would just like to know if this is possible or whether I need to try another method. The issue is in ORDER BY as code works perfectly without it.
1条答案
按热度按时间llycmphe1#
The
ORDER BY
has to be within the@SQL
text string like so:(I just moved the trailing apostrophe (') from after
Event_Table
down one line to afterDESC
.)