Sql 选择TOP@Variable causes error:";无效语法";
请参见下面的TSQL:Sql 选择TOP@Variable causes error:";无效语法";,sql,sql-server,tsql,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 = datead
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
我得到的错误是:'+@nichedailydelectionvolume+'附近的语法不正确
我以前使用过类似的变量,但从来没有使用过TOP。正如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())
但是如果没有
orderby
,就无法保证您最终会得到哪个eventid
其中candelete=getdate()
极不可能做您想做的事。不清楚名称中的数据类型candelete
是什么,但是假设通过与getdate()
的比较使用datetime,那么在执行查询时,您是否真的希望仅匹配那些精确到毫秒的行?