TSQL Writing into a Temporary Table from Dynamic SQL

后端 未结 8 1750
自闭症患者
自闭症患者 2020-12-11 04:55

Consider the following code:

SET @SQL1 = \'SELECT * INTO #temp WHERE ...\'
exec(@SQL1)
SELECT * from #temp  (this line throws an error that #temp doesn\'t ex         


        
相关标签:
8条回答
  • 2020-12-11 05:10

    Try ##temp Because your dynamic query is executed on an other fibre so you cannot see its local temporay table. instead if you declare your temporary table like global it make a sens.

    0 讨论(0)
  • 2020-12-11 05:12

    You can create temp before exec and use exec to populate the temp table.

    0 讨论(0)
  • 2020-12-11 05:18

    An example, look at "into"

    SELECT o.OrderID, o.OrderDate, od.UnitPrice, od.Quantity,
           c.CustomerID, c.CompanyName, c.Address, c.City, c.Region,
           c.PostalCode, c.Country, c.Phone, p.ProductID,
           p.ProductName, p.UnitsInStock, p.UnitsOnOrder
    INTO   #temp
    FROM   Orders o
    JOIN   [Order Details] od ON o.OrderID = od.OrderID
    JOIN   Customers c ON o.CustomerID = c.CustomerID
    JOIN   Products p ON p.ProductID = od.ProductID
    
    0 讨论(0)
  • 2020-12-11 05:20

    Didn't find a workable solution that did everything I needed so I switched to using ##global temp tables instead.

    0 讨论(0)
  • 2020-12-11 05:21

    Another method is to use all code inside the dynamic SQL

    SET @SQL1 = 'SELECT * INTO #temp WHERE ...
    SELECT * from #temp  ' 
    exec(@SQL1) 
    
    0 讨论(0)
  • 2020-12-11 05:26

    Can you not put your select after the insert into with a ; delimeter and run the two statements together?

    0 讨论(0)
提交回复
热议问题