Reputation: 1034
I have created a Function in SQL Server 2012 that I will use in a Check Constraint on a table. The function works as expected if I do:
SELECT [dbo].[CheckValidCardnumberForShellTankingen] ('700678036658047691' ,'2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B')
But when I try to set the expression in Check Constraint so:
([dbo].[CheckValidCardnumberForShellTankingen]([Volledig kaartnummer],[RollBackCode])=(1))
I get a Messaage: "Error validating constraint 'CK_MyConstraint'"
I use the Uniqueidentifier in a Where clause and the strange thing is if I replace the parameter with string containing the Uniqueidentifier I dont get this error.
Here is the Function:
-- =============================================
-- Author: Anders Pedersen
-- Create date: 2015-02-13
-- Description: Check of the Cardnumber of a transaction is valid.
-- =============================================
CREATE FUNCTION [dbo].[CheckValidCardnumberForShellTankingen]
(
-- Add the parameters for the function here
@Cardnumber NvarChar(50),
@RollBackCode NvarChar(200)
)
RETURNS BIT
AS
BEGIN
-- Declare the return variable here
DECLARE
@Result BIT
,@ResultLenght BIT
,@ResultPrefix BIT
,@CardLenght INT
,@SupplierID INT
,@UseCardnumber BIT
,@Prefix NvarChar(50)
-- Add the T-SQL statements to compute the return value here
SET @Result = 0
SET @ResultLenght = 0
SET @ResultPrefix = 0
SET @CardLenght = -1
SET @SupplierID = -1
SET @UseCardnumber = 0
SET @Prefix = ''
-- Get the UseCardnumber and the SupplierID
SELECT @UseCardnumber = C.UseCardNumber, @SupplierID = F.SupplierID
FROM Client C INNER JOIN
ClientFileUploads F ON C.ClientID = F.ClientID
WHERE F.RollBackCode = @RollBackCode
--WHERE F.RollBackCode = '2925CA00-6DD5-4F9D-AB0E-AA15DBBD388B'
-- Only carry out the check if the Client use Cards else set the check to True (1)
IF @UseCardnumber = 1
BEGIN
SELECT @CardLenght = [CardNumberLenght], @Prefix = ISNULL([Prefix],'') FROM [dbo].[Supplier] AS S WHERE S.SupplierID = @SupplierID
IF (@CardLenght IS NULL) OR (@CardLenght = 0)
BEGIN
SET @ResultLenght = 1
END
ELSE
BEGIN
IF (LEN(@Cardnumber) - @CardLenght)= 0
BEGIN
SET @ResultLenght = 1
END
ELSE
BEGIN
SET @ResultLenght = 0
END
END
IF SUBSTRING(@Cardnumber, 1, LEN(@Prefix)) = @Prefix
BEGIN
SET @ResultPrefix = 1
END
ELSE
BEGIN
SET @ResultPrefix = 0
END
IF ((@ResultLenght = 1) AND (@ResultPrefix = 1))
BEGIN
SET @Result = 1
END
ELSE
BEGIN
SET @Result = 0
END
END
ELSE
BEGIN
SET @Result = 1
END
-- Return the result of the function
RETURN @Result
END
GO
Upvotes: 0
Views: 1247
Reputation: 6612
If @RollBackCode is a uniqueidentifier, I recommend making the parameter a uniqueidentifier and not a varchar.
As Rhys Jones points out, you shouldn't use a UDF in a check constraint.
See
https://dba.stackexchange.com/questions/22297/udf-in-check-constraint-downside
If you need to check in a trigger and roll back -- SQL Server - After Insert/ For Insert - Rollback
Upvotes: 1