[英]How do I validate the Column ?? SQL
I have a table with some data. 我有一些数据表。 One of the columns is named Category and contains data like SKI or SB. 其中一列名为“类别”,其中包含SKI或SB之类的数据。
I have a function to validate and a procedure. 我有一个验证功能和一个程序。 I need to get only the columns with Category SKI. 我只需要获取带有类别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'
在where
子句中再添加一个条件,否则当您传递@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 或检查函数返回的值,然后选择PRODUCTS
表
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. 当然,它返回的所有类别,因为你的条件where
不上表中的行。 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. 您需要在表中存储的Cateogry
上运行该功能。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.