Dynamic SQL results into temp table in SQL Stored procedure

后端 未结 8 1321
孤独总比滥情好
孤独总比滥情好 2020-11-28 10:08

The code is as follows:

ALTER PROCEDURE dbo.pdpd_DynamicCall 
@SQLString varchar(4096) = null

AS

Begin

    create TABLE #T1 ( column_1 varchar(10) , colu         


        
相关标签:
8条回答
  • 2020-11-28 11:08

    You can define a table dynamically just as you are inserting into it dynamically, but the problem is with the scope of temp tables. For example, this code:

    DECLARE @sql varchar(max)
    SET @sql = 'CREATE TABLE #T1 (Col1 varchar(20))'
    EXEC(@sql)
    INSERT INTO #T1 (Col1) VALUES ('This will not work.')
    SELECT * FROM #T1
    

    will return with the error "Invalid object name '#T1'." This is because the temp table #T1 is created at a "lower level" than the block of executing code. In order to fix, use a global temp table:

    DECLARE @sql varchar(max)
    SET @sql = 'CREATE TABLE ##T1 (Col1 varchar(20))'
    EXEC(@sql)
    INSERT INTO ##T1 (Col1) VALUES ('This will work.')
    SELECT * FROM ##T1
    

    Hope this helps, Jesse

    0 讨论(0)
  • 2020-11-28 11:09
    DECLARE @EmpGroup INT =3 ,
            @IsActive BIT=1
    
    DECLARE @tblEmpMaster AS TABLE
            (EmpCode VARCHAR(20),EmpName VARCHAR(50),EmpAddress VARCHAR(500))
    
    INSERT INTO @tblEmpMaster EXECUTE SPGetEmpList @EmpGroup,@IsActive
    
    SELECT * FROM @tblEmpMaster
    
    0 讨论(0)
提交回复
热议问题