SQL Server ORDER BY when using Dynamic SQL

zc0qhyus  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(128)

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.

llycmphe

llycmphe1#

The ORDER BY has to be within the @SQL text string like so:

SET @SQL = N'SELECT TOP 1
Test_Time,
Test_ID,
FROM ' + QUOTENAME(@DBName) + '.dbo.Event_Table
ORDER BY Test_Time DESC'

(I just moved the trailing apostrophe (') from after Event_Table down one line to after DESC .)

相关问题