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:
@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):
However, the way the conditional is written, you will only add items if they are similar. Try this instead: