Problems with IF EXISTS()



当我试图通过传递@ID和@Name来运行更新信用卡类型时,我会收到一个错误,上面写着:

Msg 2786, Level 16, State 1, Procedure sp_SaveCreditCardType, Line 29
The data type of substitution parameter 1 does not match the expected type of the format specification.

问题是我的一段代码使用以下语句检查CreditCardTypes表中是否存在id:

-- make sure the ID is a valid number
        IF NOT EXISTS (SELECT * FROM CreditCardTypes WHERE ID = @ID)
            BEGIN
                RAISERROR('The Credit Card ID ''%s'' does not exist. Update Failed.', 15, 1, @ID)
                RETURN -100
            END

有人知道为什么这会给我带来错误吗?我见过很多以这种方式使用ifexists()的例子,但由于某种原因,它给了我一个错误。

这是整个过程。

CREATE PROCEDURE dbo.sp_SaveCreditCardType 
(
@ID int = null, 
@Name varchar(50),
@Description varchar(150) = null 
)
AS
DECLARE 
@Err INT
BEGIN 
SET NOCOUNT ON 
-- check to make sure a Name was passed in
IF @Name IS NULL
    BEGIN
        RAISERROR('A Name was not specified. Execution aborted.', 15, 1, @Name)
        RETURN -100
    END
-- check to see if an ID is passed
IF @ID IS NOT NULL AND @ID <> 0
    BEGIN
        -- make sure the ID is a valid number
        IF NOT EXISTS (SELECT * FROM CreditCardTypes WHERE ID = @ID)
            BEGIN
                RAISERROR('The Credit Card ID ''%s'' does not exist. Update Failed.', 15, 1, @ID)
                RETURN -100
            END
        -- update an existing credit card type
        UPDATE CreditCardTypes 
            SET Name = @Name, 
                [Description] = @Description
            WHERE ID = @ID
        SET @Err = @@ERROR
            IF @Err <> 0 GOTO ErrorHandler
    END
ELSE
    BEGIN
        -- first check to make sure the credit card type doesn't already exist
        IF NOT EXISTS (SELECT * FROM CreditCardTypes WHERE Name = @Name)
            BEGIN
                -- insert a new credit card type
                INSERT INTO CreditCardTypes (Name, [Description])
                VALUES (@Name, @Description)
                SET @Err = @@ERROR
                    IF @Err <> 0 GOTO ErrorHandler
            END
        ELSE
            RAISERROR('The Credit Card Type ''%s'' already exists. Insert failed.', 15, 1, @Name)
            RETURN -100
    END
SET @Err = @@ERROR
    IF @Err <> 0 GOTO ErrorHandler
RETURN 0
ErrorHandler:
    RAISERROR('An error occured while saving the credit card type ''%s''', 16, 1, @Name) WITH LOG
    RETURN -100
END
GO

更改:

RAISERROR('The Credit Card ID ''%s'' does not exist. Update Failed.', 15, 1, @ID)

收件人:

RAISERROR('The Credit Card ID ''%d'' does not exist. Update Failed.', 15, 1, @ID)

%s用于替换字符串。。。而CCD_ 2是int的替换参数。

MSDN 中的RAISERRO

最新更新