SELECT TOP @Variable导致错误:"语法无效"

时间:2014-11-14 14:56:40

标签: sql sql-server tsql

请参阅下面的TSQL:

declare @NicheDailyDeletionVolume int
select @NicheDailyDeletionVolume = NicheDailyDeletionVolume FROM [hq-svr-sql-05].genie2delete.dbo.dbsystem
declare @tsql as nvarchar(200)
set @tsql = 'update tbx_rrdgeniestaging set addedtime = dateadd(d,-29,getdate()) where eventid in (
select distinct top '' + @NicheDailyDeletionVolume + '' eventid from tbx_rrdgeniestaging where candelete=getdate())'
EXECUTE sp_executesql @tsql

我得到的错误是:'+ @NicheDailyDeletionVolume +'附近的语法不正确。

我之前使用过这样的变量,但从未使用TOP。

1 个答案:

答案 0 :(得分:2)

正如Gareth在他删除的答案TOP中指出的那样没有ORDER BY毫无意义。

从语法上讲,你可以对它进行参数化并传递它作为sp_executesql的参数。

DECLARE @NicheDailyDeletionVolume INT

SELECT @NicheDailyDeletionVolume = NicheDailyDeletionVolume
FROM   [hq-svr-sql-05].genie2delete.dbo.dbsystem

DECLARE @tsql AS NVARCHAR(200)

SET @tsql = '
UPDATE tbx_rrdgeniestaging
SET    addedtime = dateadd(d, -29, getdate())
WHERE  eventid IN (SELECT DISTINCT TOP (@NicheDailyDeletionVolume) eventid
                   FROM   tbx_rrdgeniestaging
                   WHERE  candelete = getdate()) 

             '

EXECUTE sp_executesql @tsql, 
                      N'@NicheDailyDeletionVolume INT',
                      @NicheDailyDeletionVolume=@NicheDailyDeletionVolume

虽然现在根本不需要动态SQL,但这并不是很明显。

TOP在括号中接受一个表达式,所以即使以下内容也可以使用

UPDATE tbx_rrdgeniestaging
SET    addedtime = dateadd(d, -29, getdate())
WHERE  eventid IN (SELECT DISTINCT TOP (SELECT NicheDailyDeletionVolume  
                                        FROM   [hq-svr-sql-05].genie2delete.dbo.dbsystem) 
                           eventid
                   FROM   tbx_rrdgeniestaging
                   WHERE  candelete = getdate()) 

但如果没有ORDER BY,则无法保证eventid您最终会遇到这种情况。