I have a table with some data. One of the columns is named Category and contains data like SKI or SB.
I have a function to validate and a procedure. I need to get only the columns with Category SKI. I know there are other simple ways to implement this...but I have an assignment and this is why I use a function and a procedure.
What am I doing wrong?
CREATE FUNCTION validateProducts(@productCategory NVARCHAR(50))
RETURNS BIT AS
BEGIN
DECLARE @returnValue BIT
IF(@productCategory LIKE 'SKI')
SET @returnValue = 1 --valid
ELSE
SET @returnValue = 0 --invalid
RETURN @returnValue
END
GO
CREATE PROCEDURE usp_ProductsRead(@productType NVARCHAR(50)) AS
BEGIN
DECLARE @productCategory NVARCHAR(50)
SET @productCategory=@productType
SELECT Category, Model
FROM PRODUCTS
WHERE dbo.validateProducts(@productCategory) = 1
END
GO
EXEC usp_ProductsRead @productType='SKI'
Add one more condtion in where
clause else you will get all the rows from table when you pass @productCategory ='SKI'
CREATE PROCEDURE usp_ProductsRead(@productType NVARCHAR(50)) AS
BEGIN
SELECT Category, Model
FROM PRODUCTS
WHERE dbo.validateProducts(@productType) = 1 and Category=@productType
END
GO
or check the value returned by function then select the PRODUCTS
table
CREATE PROCEDURE usp_ProductsRead(@productType NVARCHAR(50)) AS
BEGIN
if (select dbo.validateProducts(@productType))=1
Begin
SELECT Category, Model
FROM PRODUCTS
WHERE Category=@productType
end
else
Begin
Print 'Category is not SKI'
End
Of course it returns all categories, because your condition in the where
is not on the rows in the table. It is on the value being passed in. So, if that value matches, then all rows are returned. If the value doesn't match, then no rows are returned.
You need to run the function on the Cateogry
stored in the table. I'm not sure what column that is, but here is a guess:
CREATE PROCEDURE usp_ProductsRead AS
BEGIN
SELECT p.Category, p.Model
FROM PRODUCTS p
WHERE dbo.validateProducts(p.Category) = 1
END;
EXEC dbo.usp_ProductsRead;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.