[英]stored procedure refuses to insert data
I have the following table: 我有下表:
ThisCategoryID int IDENTITY, AUTO_INCREMENT
Title text
Type text
CategoryID int ALLOW NULLS
IsActive bit
OrderIndex int ALLOW NULLS
with this data: 与此数据:
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
and the following stored procedure: 和以下存储过程:
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
There is no item in the table with the title "Snack", yet the sp_new_category yields -1, every time I run it with the following parameters: 表中没有标题为“ Snack”的项目,但是每次我使用以下参数运行sp_new_category时,其收益都为-1:
@Title: Snack
@Type: Menu Section
@CategoryID: NULL
@IsActive: True
@OrderIndex: NULL
Can someone explain to me why that is? 有人可以向我解释为什么吗?
I believe your intent for the following conditional is to check if someone is trying enter an already existing item by Title (matched with SOUNDEX): 我相信您的意图是要满足以下条件,即检查是否有人试图按标题(与SOUNDEX匹配)输入已经存在的项目:
IF (SELECT count(*) FROM Category WHERE difference(title, @title) = 4) > 0
However, the way the conditional is written, you will only add items if they are similar. 但是,条件语句的编写方式只有在它们相似时才添加。 Try this instead:
尝试以下方法:
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
SELECT difference('Snack', 'Lunch')
UNION SELECT difference('Snack', 'Dessert')
UNION SELECT difference('Snack', 'Banh Mi')
3
1
2
None of your differences ever equal 4, so your insert is never run, so @identity
will always be -1 您的差异都不等于4,因此您的插入内容永远不会运行,因此
@identity
始终为-1
difference
is the difference in SOUNDEX encodings for text, which is an archaic hash for English names. difference
是文本的SOUNDEX编码的差异,这是英文名称的古旧哈希。 It is not suitable for foreign words. 它不适用于外来词。 If you tell us what you think you are accomplishing by using it, we may be able to help you.
如果您告诉我们您通过使用它所取得的成就,我们可能会为您提供帮助。
Am I missing something? 我想念什么吗?
The IF
statement is false so he goes to the ELSE
and puts SET @Identity = -1
. IF
语句为假,因此他去了ELSE
并将SET @Identity = -1
。 So it'll return -1
. 因此它将
return -1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.