我需要在存储过程中使用某些逻辑。所有存储过程都会执行一些逻辑规则,然后根据结果返回true或false。
伪SQL代码:
CREATE TABLE #PV ([Date] DATETIME, Dis FLOAT, Del Float, Sold Float)
INSERT #PV exec GetPVSummaryReport @ID, @PID, @From, @To
SELECT AVG(Dis) / 8 AS DisAvg, AVG(Del) AS DelAvg FROM #PV
IF DisAvg > 20 -- this is the bit I am having problems grokking
RETURN TRUE
ELSE
-- do longer calculation
你如何做这种逻辑?
关于代码的注释:表#PV有4个字段 - 提供的字段(日期,Dis,Del和Sold)。
答案 0 :(得分:2)
declare @DisAvg float
declare @DelAvg float
-- Instantiate #PV etc
select
@DisAvg = avg(Dis) / 8,
@DelAvg = avg(Del)
from
#PV
if @DisAvg > 20
return
else
-- Do something else
答案 1 :(得分:2)
为什么每个人都在制作临时表?变量表非常好(and more performant):)
让我们看看......
DECLARE @PV TABLE ([Date] DATETIME,
Dis FLOAT,
Del FLOAT,
Sold FLOAT)
INSERT INTO @PV
EXEC [dbo].[GetPVSummaryReport] @ID, @PID, @From, @To
-- Create some variables, which will contain the results.
DECLARE @DisAvg AS FLOAT,
@DelAvg AS FLOAT
-- Retrieve results into a variables.
SELECT @DisAvg = AVG(Dis) / 8, @DelAvg AVG(Del)
FROM @PV
-- Check results...
IF @DisAvg > 20
RETURN TRUE
ELSE BEGIN
-- do longer calculation
END
-- NOTE: I'm not sure where you use @DelAvg ..
-- I'm assuming it's in the 'do longer calculation' section.
祝你好运!
答案 2 :(得分:1)
LABELS 是一件美丽的事情。 LABELS 允许您使用 GOTO ,这使您可以在存储过程中编写简单的逻辑跟踪。
DECLARE @Result int
SET @Result = 1 -- 1=True 0=False
IF TEST1 Failed
BEGIN
SET @Result = 0
GOTO ENDPROCESSING
END
IF TEST2 Failed
BEGIN
SET @Result = 0
GOTO ENDPROCESSING
END
IF TEST3 Failed
BEGIN
SET @Result = 0
GOTO ENDPROCESSING
END
ENDPROCESSING:
SELECT @Result
答案 3 :(得分:0)
您需要声明一个变量并选择它
DECLARE @DisAvg DOUBLE, @DelAvg DOUBLE
SELECT @DisAvg = AVG(Dis) / 8, @DelAvg = AVG(Del) #PV
IF @DisAvg > 20 -- this is the bit I am having problems grokking
RETURN 1
ELSE
-- do longer calculation
使用正确的Dis字段类型声明。
修改 - 更正了返回值。
答案 4 :(得分:-1)
DECLARE @DisAvg DECIMAL
DECLARE @ReturnValue bit
//使用SET或SELECT将值赋给@DisAvg
IF (@DisAvg > 20)
BEGIN
SET @ReturnValue = 1
END
ELSE
BEGIN
-- do longer calculation
SET @ReturnValue = 0
END
SELECT @ReturnValue
只能从RETURN
语句返回整数,您可以使用SELECT
代替