SQL Server裡函數的兩種用法(可以代替游標)
1. 因為update裡不能用存儲過程,然而要根據更新表的某些字段還要進行計算。我們常常采用游標的方法,這裡用函數的方法實現。
函數部分:
以下是引用片段:
CREATE FUNCTION [DBO].[FUN_GETTIME] (@TASKPHASEID INT)
RETURNS FLOAT AS
BEGIN
DECLARE @TASKID INT,
@HOUR FLOAT,
@PERCENT FLOAT,
@RETURN FLOAT
IF @TASKPHASEID IS NULL
BEGIN
RETURN(0.0)
END
SELECT @TASKID=TASKID,@PERCENT=ISNULL(WORKPERCENT,0)/100
FROM TABLETASKPHASE
WHERE ID=@TASKPHASEID
SELECT @HOUR=ISNULL(TASKTIME,0) FROM TABLETASK
WHERE ID=@TASKID
SET @RETURN=@HOUR*@PERCENT
RETURN (@RETURN)
END
調用函數的存儲過程部分
以下是引用片段:
CREATE PROCEDURE [DBO].[PROC_CALCCA]
@ROID INT
AS
BEGIN
DECLARE @CA FLOAT
UPDATE TABLEFMECA
SET
Cvalue_M= ISNULL(MODERATE,0)*ISNULL(FMERATE,0)*ISNULL(B.BASFAILURERATE,0)*[DBO].[FUN_GETTIME](C.ID)
FROM TABLEFMECA ,TABLERELATION B,TABLETASKPHASE C
WHERE ROID=@ROID AND TASKPHASEID=C.ID AND B.ID=@ROID
SELECT @CA=SUM(ISNULL(Cvalue_M,0)) FROM TABLEFMECA WHERE ROID=@ROID
UPDATE TABLERELATION
SET CRITICALITY=@CA
WHERE ID=@ROID
END
GO