2016-09-27 83 views
1

以下是我的示例查詢,任何人都可以告訴我如何在WITH子句中執行動態查詢。如何在SQL Server中的WITH子句中執行動態查詢

DECLARE @V_TBLID NVARCHAR(MAX) = 1, @V_QUERY NVARCHAR(MAX) = '', @IN_PAGESIZE INT = 5, @IN_PAGEINDEX INT = 1;  
SET @V_QUERY = N'SELECT * FROM MYTABLE'+ @V_TBLID; 
WITH RESULTS AS 
(
    EXEC(@V_QUERY) 
) 
SELECT * FROM RESULTS 
WHERE [row_num] BETWEEN (((@IN_PAGEINDEX - 1) * @IN_PAGESIZE) + 1) AND (@IN_PAGEINDEX * @IN_PAGESIZE); 

回答

2

您不能在CTE內部使用EXECUTE。

要使用您正在嘗試的方法執行此操作,您需要將整個查詢封裝到動態SQL語句中,動態構建CTE(WITH語句),並將@V_QUERY附加到該動態SQL語句。

例如像

DECLARE @SQL NVARCHAR(MAX) 
SET @SQL = 
    'WITH Results AS (' + @V_QUERY + ') 
    SELECT * 
    FROM Results 
    WHERE [row_num] BETWEEN (((@IN_PAGEINDEX - 1) * @IN_PAGESIZE) + 1) AND (@IN_PAGEINDEX * @IN_PAGESIZE)' 

EXECUTE sp_executesql @SQL, N'@IN_PAGEINDEX INT, @IN_PAGESIZE INT', @IN_PAGEINDEX, @IN_PAGESIZE 

強制性旁註 - 無論使用動態sql,確保您防範SQL注入風險!

+0

謝謝@AdaTheDev – Srinivas