【发布时间】:2018-09-30 13:10:36
【问题描述】:
当我在触发器之外执行 UDF 时结果不一样
在触发器中执行时,UDF 总是返回 true
但在触发器之外结果是真还是假
ALTER FUNCTION [dbo].[MandatExist]
(
@Numero int,
@IdBranche int,
@Exercice int
)
RETURNS bit
AS
BEGIN
DECLARE @Result bit
DECLARE @Nbr int
DECLARE @Categ int
SELECT @Categ = CategorieNumero
FROM Branche
WHERE IdBranche = @IdBranche
SELECT @Nbr=COUNT(*)
FROM Mandat AS M INNER JOIN Branche AS B ON M.IdBranche=B.IdBranche
WHERE (Numero = @Numero) AND (B.CategorieNumero = @Categ) AND (Exercice = @Exercice)
IF @Nbr = 0
SET @Result = 0
ELSE
SET @Result = 1
RETURN @Result
END
触发器调用 MandatExist 来获取号码是否存在
ALTER TRIGGER [dbo].[ValidInsertUpdate_Mandat]
ON [dbo].[Mandat]
FOR INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Cloturer AS bit
DECLARE @Exercice AS int
DECLARE @IdBranche AS int
DECLARE @Numero AS int
DECLARE @Message AS nvarchar(100)
SELECT @Cloturer=Cloturer, @Exercice=Exercice, @Numero=Numero, @IdBranche=IdBranche
FROM INSERTED
IF (dbo.MandatExist(@Numero, @IdBranche, @Exercice)=1)
BEGIN
SET @Message = 'Numero de mandat existant.'
RAISERROR(@Message, 16, 1)
ROLLBACK TRAN
END
【问题讨论】:
-
请在问题后面附加 UDF 的定义。
-
如何从触发器调用 UDF?所述触发器的代码是什么?调用时所述数据的值是多少?我们看不到您看到的内容,因此除非您向我们展示,否则我们无能为力。
-
inserted和deleted是表,因此它们可以表示集合操作的结果。假设触发器总是只处理一行,而设计触发器通常是一个糟糕的计划。如果您绝对确定不会超过一排,那么请添加对行数的检查,并使用RaIsError或Throw明确告知稍后来的人他们有试图执行不可接受的语句。 (if ( select Count(*) from inserted ) > 1 RaIsError( 'FooTable_Insert: No more than one row may be processed.', 25, 42 ) with log)
标签: sql sql-server tsql triggers user-defined-functions