I have the following stored procedure:
CREATE PROCEDURE oc.add_discount (@course_id INT = '',
@level VARCHAR(100) = '',
@language VARCHAR(100) = '',
@series_name VARCHAR(100) = '',
@discount DECIMAL(5,4) = 0.0)
AS
BEGIN
SET @level = ISNULL(@level,'')
SET @language = ISNULL(@language,'')
SET @series_name = ISNULL(@series_name,'')
UPDATE oc.price
SET discount = @discount,
--discount based always on the original price
price = price/(1-discount)*(1-@discount)
WHERE
(@course_id NOT IN (SELECT course_id FROM oc.courses)
OR course_id IN (@course_id)) AND
(@level NOT IN (SELECT level FROM oc.level)
OR course_id IN (SELECT c.course_id
FROM oc.courses c
JOIN oc.level l ON c.level_id = l.level_id
WHERE l.level = LOWER(@level))) AND
(@language NOT IN (SELECT language FROM oc.language)
OR course_id IN (SELECT c.course_id
FROM oc.courses c
JOIN oc.language l ON c.language_id = l.language_id
WHERE l.language = UPPER(LEFT(@language,1))+LOWER(SUBSTRING(@language,2,LEN(@language))))) AND
(@series_name NOT IN (SELECT series_name FROM oc.series)
OR course_id IN (SELECT c.course_id
FROM oc.courses c
JOIN oc.series s ON c.series_id = s.series_id
WHERE s.series_name = @series_name))
IF @@ROWCOUNT<1
RAISERROR('Ooops something went wrong. No discount has been added. Avoid NULL or missing values, use '' instead!', 16, 0);
END;
My problem is that the procedure is working properly in most of the cases however if a parameter is null it doesn't update anything and if a parameter in the middle is missing I get an error. I managed the problem with an error message but I would like to find a more elegant solution. Could anyone help me,please?
EXEC oc.add_discount 0.1, 1 ---- this query gives 10% discount for course ID 1
EXEC oc.add_discount 0.1, '', 'beginner', '', '' ---- this query 10% discount for every beginner course
EXEC oc.add_discount 0.1, NULL, 'beginner', '','' ---- "0 rows affected"
EXEC od.add_discount 0.1, ,'beginner', , ---- "Incorrect syntax near ','."