我正在尝试创建一个如下所示的SQL proc:
If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '1')
Begin
// do this
End
Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '0')
Begin
// do this
End
直到这里,它才能正常运作。但是,接下来的两个陈述不起作用,我想知道为什么。
Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowNoCustomers' And ParValue = '1')
If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '1')
Begin
//do this
End
Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowNoCustomers' And ParValue = '1')
If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '0')
Begin
//do this
End
默认情况下,ShowNoCustomer Par值为100%肯定值1,但我可以在应用程序中将其更改为0.
没有错误,但是当ShowNoCustomer为1时,我只想做它想做的sql。
答案 0 :(得分:4)
我认为你的逻辑是有缺陷的,你没有完全使用开始/结束来嵌套应有的一切。这应该是等效的,并且是正确的逻辑:
Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowNoCustomers' And ParValue = '1')
Begin
If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '1')
Begin
//do this
End
Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '0')
Begin
//do this
End
End
不需要重复Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowNoCustomers' And ParValue = '1')
,缺少开始/结束会使您对执行路径感到困惑。
或者,当ShowStartEndTimeInd值为0时,此版本更简洁,并且会生成1个查询而不是2个:
Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowNoCustomers' And ParValue = '1')
Begin
--using a variable so we only have to do the query once
Declare @ShowStartEndTimeVal varchar(5)
Select @ShowStartEndTimeVal = ParValue From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd'
If @ShowStartEndTimeVal = '1'
Begin
//do this
End
Else If @ShowStartEndTimeVal = '0'
Begin
//do this
End
End
答案 1 :(得分:1)
我认为在else ifs中将你的sub ifs嵌入到开头/结尾对中可以解决这个问题(确保每个语句在" true"上发出)
Else If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowNoCustomers' And ParValue = '1')
begin
If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '1')
Begin
//do this
End
/*Else*/ If exists (Select 1 From ST_Setting Where Parameter = 'KWI_TR_ShowStartEndTimeInd' And ParValue = '0')
Begin
//do this
End
end