我之前遇到过这个问题,并且想知道为什么“开始”& “结束”需要产生正确的值。 if语句是单例,不需要“开始”和“ “结束”,if中的多个语句需要它,如果省略,则在尝试创建/更改过程时会生成执行错误。
有关为什么在MS SQL中发生此行为的任何想法?????
谢谢,克雷格
- 结果集2返回正确的值。
SQL。
Declare @Qty DECIMAL(10,2), @UOM VARCHAR(5), @CasePack Numeric(7,1), @CaseQty Numeric(11, 4), @im_weigh_item SmallInt, @rank_wi_ven_ctg Char(1), @po_qty_uom Char(1), @po_Qty float
Select
-- these 2 Params are Const in this process
@im_weigh_item =0, @rank_wi_ven_ctg = 'C',
-- Set Values
@UOM = 'C' , @po_Qty_uom = 'M', @po_Qty = 3, @casepack =6, @Qty = 2
/*
Check and Set vars. accordingly
This Conditional Block Generates no errors, but the results are incorrect
** NO "Begin" & End"
*/
If(@im_weigh_item=1)
If(@rank_wi_ven_ctg='U')
Select @UOM = 'U'
Else
If(@po_Qty_uom != 'C' )
If(@po_Qty!=@casepack)
Select @UOM = 'U', @Qty = @Qty * @po_Qty
-- Debug
Select @po_Qty_uom as po_Qty_uom, @UOM as UOM, @casepack as casepack, @po_Qty as po_Qty, @Qty as Qty
-- Debug
-- reset vars, test 2
Select @UOM = 'C' , @po_Qty_uom = 'M', @po_Qty = 3, @casepack =6, @Qty =2
/*
*** Works *** Calcs Correctly
Check and Set vars. accordingly
*** This Block uses the "Begin" & "End"
*/
If(@im_weigh_item=1)
begin
If(@rank_wi_ven_ctg='U')
Select @UOM = 'U'
end
Else
begin
If(@po_Qty_uom != 'C' )
If(@po_Qty!=@casepack)
Select @UOM = 'U', @Qty = @Qty * @po_Qty
end
-- Debug
Select @po_Qty_uom as po_Qty_uom, @UOM as UOM, @casepack as casepack, @po_Qty as po_Qty, @Qty as Qty
-- Debug
答案 0 :(得分:4)
将明确的BEGIN
和END
添加到您的损坏版本会产生这种情况, 与您的工作版本具有相同的逻辑:
If(@im_weigh_item=1)
BEGIN
If(@rank_wi_ven_ctg='U')
BEGIN
Select @UOM = 'U'
END
Else -- this "else" is associated with the wrong "if"
BEGIN
If(@po_Qty_uom != 'C' )
BEGIN
If(@po_Qty!=@casepack)
BEGIN
Select @UOM = 'U', @Qty = @Qty * @po_Qty
END
END
END
END
答案 1 :(得分:4)
ELSE语句总是绑定到没有ELSE的最近的前一个IF,所以你的
If(@im_weigh_item=1)
If(@rank_wi_ven_ctg='U')
Select @UOM = 'U'
Else
If(@po_Qty_uom != 'C' )
If(@po_Qty!=@casepack)
Select @UOM = 'U', @Qty = @Qty * @po_Qty
被解释为:
If(@im_weigh_item=1) begin
If(@rank_wi_ven_ctg='U') begin
Select @UOM = 'U'
end
Else begin
If(@po_Qty_uom != 'C' ) begin
If(@po_Qty!=@casepack) begin
Select @UOM = 'U', @Qty = @Qty * @po_Qty
end
end
end
end
答案 2 :(得分:3)
我认为没有BEGIN和END的If应该只包含一条指令。 我建议为每个IF添加BEGIN .. END,以帮助保持编码的一致性。