快捷搜索:  test  as

分析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

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

IF (@ENID=NULL) OR (@PARTID=NULL) OR (@SOURCEID=NULL) OR (@QUALITYID=NULL)

BEGIN

RETURN(0.0)

END

SELECT @QXS= ISNULL(XS,0) FROM TABLEQUALITY WHERE ID=@QUALITYID

SELECT @G=ISNULL(FRATE_G,0) FROM TABLEFAILURERATE

WHERE (SUBKINDID=@PARTID) AND( ENID=@ENID) AND ( DATASOURCEID=@SOURCEID)

AND( ( (ISNULL(MINCOUNT,0)=ISNULL(@COUNT,0)))

OR(ISNULL(@COUNT,0)>ISNULL(MAXCOUNT,0)))

SET @RATE=ISNULL(@QXS*@G,0)

RETURN (@RATE)

END

调用函数的存储历程部分:

CREATE PROC PROC_FAULTRATE

@PARTID INTEGER, @QUALITYID INTEGER, @SOURCEID INTEGER, @COUNT INTEGER,

@ROID INT, @GRADE INT,@RATE FLOAT=0 OUTPUTAS

BEGIN

DECLARE

@TASKID INT

SET @RATE=0.0

SELECT @TASKID=ISNULL(TASKPROID,-1) FROM TABLERELATION WHERE

ID=(SELECT PID FROM TABLERELATION WHERE ID=@ROID)

IF (@TASKID=-1) OR(@GRADE=1) BEGIN

SET @RATE=0

RETURN

END

SELECT @RATE=SUM([DBO].[FUN_RATE] (@PARTID,ENID,@SOURCEID,

@QUALITYID,@COUNT) *ISNULL(WORKPERCENT,0)/100.0)

FROM TABLETASKPHASE

WHERE TASKID=@TASKID

END

GO

函数还可以返回表等,盼望大年夜家一路评论争论sqlserver里函数的妙用。

68476636-8007)

您可能还会对下面的文章感兴趣: