存储过程拒绝插入数据

时间:2011-12-12 17:24:53

标签: sql sql-server-2005 stored-procedures

我有下表:

ThisCategoryID int   IDENTITY, AUTO_INCREMENT
Title          text
Type           text
CategoryID     int   ALLOW NULLS
IsActive       bit
OrderIndex     int   ALLOW NULLS

有这些数据:

ThisCategoryID  Title    Type          CategoryID  IsActive  OrderIndex
0               Lunch    Menu Section  NULL        True      3
2               Dessert  Menu Section  NULL        True      1
3               Banh Mi  Food Item     0           True      4

以及以下存储过程:

ALTER PROCEDURE [dbo].[sp_new_category]
    @Title text,
    @Type text,
    @CategoryID int = null,
    @IsActive bit, 
    @OrderIndex int = null
AS
    DECLARE @Identity int
    IF (SELECT count(*) FROM Category WHERE difference(title, @title) = 4) > 0
    BEGIN
        INSERT INTO Category (Title, Type, CategoryID, IsActive, OrderIndex) VALUES (@Title, @Type, @CategoryID, @IsActive, @OrderIndex)
        SET @Identity = scope_identity()
    END
    ELSE
    BEGIN
        SET @Identity = -1
    END
    SELECT @Identity AS ID
    RETURN @Identity

表中没有标题为“Snack”的项目,但每次使用以下参数运行时,sp​​_new_category都会产生-1:

 @Title: Snack
 @Type: Menu Section
 @CategoryID: NULL
 @IsActive: True
 @OrderIndex: NULL

有人能解释一下为什么会这样吗?

3 个答案:

答案 0 :(得分:2)

我相信您对以下条件的意图是检查某人是否正在尝试按标题输入已存在的项目(与SOUNDEX匹配):

IF (SELECT count(*) FROM Category WHERE difference(title, @title) = 4) > 0

但是,编写条件的方式只会在相似的情况下添加项目。试试这个:

DECLARE @Identity int
IF (SELECT count(*) FROM Category WHERE difference(title, @title) = 4) > 0
BEGIN
    SET @Identity = -1
END
ELSE
BEGIN
    INSERT INTO Category (Title, Type, CategoryID, IsActive, OrderIndex) VALUES (@Title, @Type, @CategoryID, @IsActive, @OrderIndex)
    SET @Identity = scope_identity()
END
SELECT @Identity AS ID
RETURN @Identity

答案 1 :(得分:2)

SELECT difference('Snack', 'Lunch')
UNION SELECT difference('Snack', 'Dessert')
UNION SELECT difference('Snack', 'Banh Mi')

3
1
2

你的差异都不等于4,所以你的插入永远不会运行,所以@identity总是-1

difference是SOUNDEX编码对文本的区别,这是英文名称的古老哈希。它不适合外来词。如果您通过使用它告诉我们您认为您正在完成的任务,我们可能会帮助您。

答案 2 :(得分:0)

我错过了什么吗?

IF语句为false,因此他转到ELSE并放置SET @Identity = -1。所以它会return -1