开发者

Assign case statement result to variable

When I try to run the following statement, I get this error:

"A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."

DECLARE @OFR DECIMAL(18,2)
;
SELECT @OFR = 
CASE SUM(ofr.Quantity)
WHEN 0 THEN 0 
ELSE SUM开发者_StackOverflow(ofr.Gross) / SUM(ofr.Quantity)
END
FROM DistributionCosts ofr
;
SELECT @OFR

I just want to stick the result of that case statement into a variable and I'm getting stuck here.

Any ideas?

Thanks.


Are you sure this is where your error is? I just ran the statement below and it worked:

DECLARE @OFR DECIMAL(18,2)
;
with DistributionCosts  as
(
  select 1 as quantity, 5 as gross
  union
  select 5 , 20
)
SELECT @OFR = 
CASE SUM(ofr.Quantity)
WHEN 0 THEN 0 
ELSE SUM(ofr.Gross) / SUM(ofr.Quantity)
END
FROM DistributionCosts ofr

;
SELECT @OFR

If I select a column in addition to setting a variable I do get your error... If you are selecting another column you will need to either stop selecting that column or assign that column to a local variable as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜