我正在尝试执行包含多个子查询的SQL查询,然后将其中的一些部分分配给局部变量。不幸的是,我遇到了使语法正确的问题。
我的查询如下
declare @temp1 varchar(200)
declare @temp2 varchar(200)
select case when cnt>0 then 'RouteA' else 'RouteB' end as Route from
( select
(
(select case when (req.Avg > 10) then 1 else 0 end from
(select count(val) as Avg from T1) req) +
(select case when (req.Avg > 10) then 1 else 0 end from
(select count(val) as Avg from T2) req)
) as cnt) t
我需要做的是将以下子查询的值赋给@ temp1:
(select case when (req.Avg > 10) then 1 else 0 end from
(select count(val) as Avg from T1) req)
这个子查询到temp2:
(select case when (req.Avg > 10) then 1 else 0 end from
(select count(val) as Avg from T2) req)
我尝试过多种方法,但不断出现语法错误。
任何帮助将不胜感激!
谢谢你, 查理
答案 0 :(得分:2)
您不能在同一个选择中混合变量赋值和结果集。您的SQL也有其他问题。我不认为你可以从count()的结果中选择。
为什么不分配变量,如果需要,请对它们进行选择?
IF (select count(val) as Avg from T1) > 10
SET @temp1 = 1
ELSE
SET @temp1 = 0
如果需要
,您也可以在选择中执行此操作SELECT @temp1 = CASE WHEN (select count(val) as Avg from T1) > 10 THEN 1 ELSE 0 END