EXEC Sp_executesql中的错误

时间:2014-11-23 08:18:30

标签: sql sql-server stored-procedures

我写了这个查询

DECLARE @Base nvarchar(200) 

SET @Base = 'WITH Base AS (SELECT Id, ROW_NUMBER() OVER (ORDER BY Id DESC) RN FROM'+    QUOTENAME(@SampleWorkTbl)+')'

EXEC Sp_executesql @Base output

SELECT Top 15
    [Id]
    ,IsLock
    ,[Title]
    ,[Desc]
    ,[ImageAddress]
    ,[Time]
FROM 
    [Sorin].[dbo].[News]
WHERE 
    [Id] IN (SELECT TOP 15 Id 
             FROM Base 
             WHERE RN > ((@Count-1) * 15) 
             ORDER BY Id DESC)
ORDER BY 
    [Id] DESC

我的问题在这一行

WHERE [Id] IN (SELECT TOP 15 Id From Base WHERE RN > ((@Count-1)*15) ORDER BY Id DESC)

Base无法识别。

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

我认为这是你想要实现的目标

DECLARE @Base NVARCHAR(200)

SET @Base = 'WITH Base AS (SELECT Id, ROW_NUMBER() OVER (ORDER BY Id DESC) RN FROM'
            + Quotename(@SampleWorkTbl) + ')
    select * into ##temp from base'

EXEC Sp_executesql
  @Base

SELECT *
FROM   ##temp

SELECT TOP 15 [Id],
              IsLock,
              [Title],
              [Desc],
              [ImageAddress],
              [Time]
FROM   [Sorin].[dbo].[News]
WHERE  [Id] IN (SELECT TOP 15 Id
                FROM   ##temp
                WHERE  RN > ( ( @Count - 1 ) * 15 )
                ORDER  BY Id DESC)
ORDER  BY [Id] DESC