动态SQL的where子句中的临时表值

时间:2018-10-12 11:04:42

标签: sql-server dynamic-sql temp-tables

在动态SQL的where子句中使用临时表中的值时,需要了解以下语法是否正确

DECLARE @sqlQ nvarchar(1000);

if OBJECT_ID('tempdb..#Tem') is not null BEGIN DROP tABLE #Tem END
create table #Tem
(order nvarchar(10))

insert into #Tem
Select orderID from customerdetails where  OrderID >100


  SET @sqlQ = N'UPDATE FINALTable SET Highvalcusomer=1 where 
   orderno=#Tem.order'
      EXEC @sqlQ 

1 个答案:

答案 0 :(得分:1)

一口气做

   UPDATE 
    FINALTable 
   SET 
    Highvalcusomer=1 
   where 
     orderno IN (Select orderID from customerdetails where  OrderID >100)

或者如果您真的想使用动态SQL

SET @sqlQ = N'UPDATE FINALTable SET Highvalcusomer=1 where 
            orderno IN (Select orderID from #Tem)'
EXEC (@sqlQ )

#Tem将在动态SQL范围内