表变量和错误“必须声明标量变量”
Posted
技术标签:
【中文标题】表变量和错误“必须声明标量变量”【英文标题】:Table variable and error "Must declare the scalar variable" 【发布时间】:2016-12-16 14:48:07 【问题描述】:我需要为 ~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];
然后我得到错误:
消息 137,第 15 级,状态 2,第 3 行 必须声明标量变量“@UserDailyStatsForCategories”。
发生了什么事?
【问题讨论】:
@CategoryID
是您声明的表@UserDailyStatsForCategories
的列。稍后您尝试像使用声明的变量一样使用它...
【参考方案1】:
正确的语法如下:
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
【讨论】:
是的,如果要将值放入表变量中,则必须加入表变量才能在更新查询中访问它们。您也可以使用相关子查询,但这更复杂且更慢。学习连接语法要好得多。以上是关于表变量和错误“必须声明标量变量”的主要内容,如果未能解决你的问题,请参考以下文章