表变量和错误“必须声明标量变量”

时间:2016-12-16 14:48:08

标签: sql sql-server

我需要为~20行创建临时表或变量。

DECLARE @UserDailyStatsForCategories TABLE (
        CategoryId uniqueidentifier not null,
        [Date] date not null,
        [Unique users] int not null,
        [Returning users] int not null,
        [New users] int not null
    );

insert into @UserDailyStatsForCategories (CategoryId, [Date], [Unique users], [Returning users], [New users])                               
     select 
     @CategoryId,
      eventdate,
      count(*),
      count(case when cnt > 1 then 1 end),
      count(case when cnt = 1 then 1 end)
    from
    (
      select cast(eventtime as date) as eventdate, userid, count(*) as cnt
      from telemetrydata
      where [dbo].[TelemetryData].[DiscountId] = @DiscountId
                and [dbo].[TelemetryData].[EventName] = 'DiscountClick'
      group by cast(eventtime as date), userid
    ) date_user
    group by eventdate;

它有效,但是当我添加它时:

update CategoryDailyStatsTemp 
set
    [CategoryDailyStatsTemp].[Unique users] = @UserDailyStatsForCategories.[Unique users],
    [CategoryDailyStatsTemp].[Returning users] = @UserDailyStatsForCategories.[Returning users],
    [CategoryDailyStatsTemp].[New users] = @UserDailyStatsForCategories.[New users]
where [CategoryDailyStatsTemp].[Id] = @UserDailyStatsForCategories.CategoryId
and [CategoryDailyStatsTemp].[Date] = @UserDailyStatsForCategories.[Date];

然后我收到了错误:

  

Msg 137,Level 15,State 2,Line 3   必须声明标量变量“@UperDailyStatsForCategories”。

发生了什么事?

1 个答案:

答案 0 :(得分:6)

正确的语法如下:

Update  C
Set     [Unique users]    = U.[Unique users],
        [Returning users] = U.[Returning users],
        [New users]       = U.[New users]
From    CategoryDailyStatsTemp       C
Join    @UserDailyStatsForCategories U   On  U.CategoryId = C.Id
                                         And U.Date = C.Date