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=@TASKPHASEIDSELECT @HOUR=ISNULL(TASKTIME,0) FROM TABLETASK
WHERE
ID=@TASKIDSET @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=@ROIDUPDATE TABLERELATION
SET
CRITICALITY=@CA WHERE
ID=@ROIDEND
GO
2. 我们要根据某表的某些记录,先计算后求和,因为无法存储中间值,平时我们也用游标的方法进行计算。但sqlserver2000里支持
SUM ( [ ALL | DISTINCT ] expression )
expression
是常量、列或函数,或者是算术、按位与字符串等运算符的任意组合。因此我们可以利用这一功能。
函数部分:
CREATE FUNCTION [DBO].[FUN_RATE] (@PARTID INT,@ENID INT,@SOURCEID INT, @QUALITYID INT,@COUNT INT)
RETURNS FLOAT AS
BEGIN
DECLARE @QXS FLOAT, @G FLOAT, @RATE FLOAT