我希望基于表中的单个值在CASE语句中执行3种不同的操作。 1.设置局部变量以用于多部分项目跟踪号。 2.设置第二个局部变量,以用于多部分项目跟踪号的不同部分。 3.为第2部分增加一个计数器。
DECLARE @location char(1) = 'P';
DECLARE @fundSource char(4) = 'SPRO';
DECLARE @fy char(2) = '19';
DECLARE @type char(2) = '';
DECLARE @loc_tn char(6) = '000000';
DECLARE @BR_i int = 1;
DECLARE @AR_i int = 0;
SELECT @type =
CASE
WHEN proposalTypeID IN (1, 6) THEN 'BR'
WHEN proposalTypeID IN (2, 7) THEN 'AR'
END
SELECT @loc_tn =
CASE
WHEN proposalTypeID IN (1, 6) THEN right('000000' + cast(@BR_i+1 as varchar(6)), 6)
WHEN proposalTypeID IN (2, 7) THEN right('000000' + cast(@AR_i+1 as varchar(6)), 6)
END
FROM proposalPackage WHERE proposalPackageID IN (17)
DECLARE @trackingNumber char(20) = LTRIM(RTRIM(@location + '-' + @fundSource + '-' + @type + '-' + @fy + '-' + @loc_tn))
SELECT @trackingNumber
我可以注释掉任何一个CASE语句,并且查询运行良好。当我尝试将它们都保留在查询中时,我收到FIRST CASE语句的错误“无效的列名proposalTypeID”。
我确定这是我忽略的东西,但我看上去似乎都在显示这是正确的语法。而且我找不到任何原因不能在后续的CASE语句中使用相同的字段。
帮助?
谢谢, 鲍勃
答案 0 :(得分:2)
用逗号替换第二个select
:
SELECT @type =
CASE
WHEN proposalTypeID IN (1, 6) THEN 'BR'
WHEN proposalTypeID IN (2, 7) THEN 'AR'
END
, @loc_tn =
CASE
WHEN proposalTypeID IN (1, 6) THEN right('000000' + cast(@BR_i+1 as varchar(6)), 6)
WHEN proposalTypeID IN (2, 7) THEN right('000000' + cast(@AR_i+1 as varchar(6)), 6)
END
FROM proposalPackage WHERE proposalPackageID IN (17)