SQL Server从临时表中选择另一个临时表

时间:2013-01-03 10:55:15

标签: sql-server-2008-r2

我在存储过程中有这个:

select * into #temp_UNION from 
(
  SELECT 6 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (588,1,6)
   UNION all
   SELECT 8 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (558,1,8)
 ) a

给出:

interaction type  historyid         incentiveprogramid       points  
 6              1                  1               50
 6                  1                  4                   50
 6              1                      5                   50
 8                  1                  3                  100
 8              1                  4              100

然后我有:

select tu.InteractionType,ipc.Name,tu.Points from #temp_UNION tu
 inner join Incentive.IncentiveProgramCultures ipc
on tu.IncentiveProgramId = ipc.IncentivePrograms_IncentiveProgramId
 inner join Zinc.Users zu
on zu.Cultures_DefaultCultureId = ipc.IncentiveProgramCultureId
 where zu.UserId = 588


6   India - Q2 Incentive    50
8   India - Q2 Incentive    100

现在我需要通过使用我从上面得到的名字和点来组成HintText,这是我的#CategoriesTable(之前定义的)中的一个字段

UPDATE #CategoriesTable
SET HintText = CASE WHEN HasAssessment = 1 
                    THEN 'Program ' + tu.name + ' will earn you ' + tu.points
                    ELSE 'With No Assessment' 
                END 

但是我在tu.Name上收到错误:多部分标识符无法绑定? 我怎么能实现?我应该使用其中包含2行的另一个临时表吗?

这里是新代码:

 select * into #temp_UNION from 
(
 SELECT 6 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (588,1,6)
 UNION all
 SELECT 8 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (558,1,8)
 ) a

 select tu.InteractionType,ipc.Name,tu.Points,zu.UserId  into #temp1 from #temp_UNION tu
 inner join Incentive.IncentiveProgramCultures ipc
 on tu.IncentiveProgramId = ipc.IncentivePrograms_IncentiveProgramId
 inner join Zinc.Users zu
 on zu.Cultures_DefaultCultureId = ipc.IncentiveProgramCultureId
 where zu.UserId = 588

Select * from #temp1 t
UPDATE #CategoriesTable
  SET HintText = CASE WHEN HasAssessment = 1 
                    THEN 'Program ' + t.Name + ' and points = ' + t.Points
                    ELSE 'With No Assessment' 
                END 
FROM #temp1 t
WHERE t.userId = #CategoriesTable.UserId

DROP TABLE #temp_UNION 
DROP TABLE #temp1

SELECT *
FROM #CategoriesTable

我没有得到#CategoriesTable?

1 个答案:

答案 0 :(得分:1)

您必须在更新子句

中指定“tu”别名
UPDATE #CategoriesTable
SET HintText = CASE WHEN HasAssessment = 1 
                THEN 'Program ' + tu.name + ' will earn you ' + tu.points
                ELSE 'With No Assessment' 
            END 
FROM #temp_UNION tu
WHERE tu.? = #CategoriesTable.? --JOIN condition