本文介绍了动态SQL结果INTO#临时表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须执行动态SQL SELECT查询并将结果放入#TempTable.

I have to Execute a dynamic SQL SELECT Query And put Results into a #TempTable.

DECLARE @StateId CHAR(3)='StateID';
DECLARE @DeptId CHAR(15)='DeptID';
DECLARE @Query VARCHAR(MAX)='Select Columns With Joins Passed From Front End'
DECLARE @Where VARCHAR(500);
DECLARE @FinalQuery VARCHAR(MAX)='';
SET @Where='Some Where Condition';
SET @FinalQuery='SELECT '+@Query+' '+@Where+''
EXEC(@FinalQuery) -- Want To INSERT THIS Result IN SOME `#TempTable`
                  -- SO that I can perform Some Operations On `#TempTable`

从动态SQL SELECT返回的ALSO No列是动态的.

ALSO No Of columns returned From Dynamic SQL SELECT Are Dynamic.

谢谢

推荐答案

尝试以下示例

DECLARE @StateId CHAR(3)='StateID';
DECLARE @DeptId CHAR(15)='DeptID';
DECLARE @Query VARCHAR(MAX)='*'  -- here you pass your query
DECLARE @Where VARCHAR(500);
DECLARE @FinalQuery VARCHAR(MAX)='';
SET @Where='from tablename where condition';
SET @FinalQuery='SELECT '+@Query+' INTO #temptablename '+@Where;
EXEC(@FinalQuery)

注意:如果在sp执行后需要使用temtable,则使用##而不是#,那么我们可以访问它,也可以使用持久性临时表

Note:If you need to use temtable after sp execution then use ## rather than # then we can access it or we can use persistent temporary table

这篇关于动态SQL结果INTO#临时表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 02:30