[英]how to define a variable inside a stored procedure query?
I am newbie to Stored Procedures. 我是存储过程的新手。 how can I define a variable to be used inside a sql query?
如何定义要在sql查询中使用的变量? here is my code but when I run this stored procedure I get this error:
这是我的代码,但是当我运行此存储过程时,出现此错误:
An expression of non-boolean type specified in a context where a condition is expected, near 'or'.
在需要条件的上下文中在“或”附近指定的非布尔类型的表达式。
this is my code: 这是我的代码:
declare @sql nvarchar(MAX)
Declare @availabilityStatus nvarchar(MAX)
BEGIN
IF @Availability = 1
set @availabilityStatus = '0 or 1 or 2'
ELSE
set @availabilityStatus = '1'
set @sql =
'SELECT Distinct P.ProductId, P.BrandId, P.[' + @OrderIndex + '] FROM Products P INNER JOIN ProductStores PS ON P.ProductId = PS.ProductId ' +
'Where PS.StoreId = @StoreId and (PS.Status = ' + @availabilityStatus + 'or PS.AvailabilityRank < '
this @Availability
variable is an input that I have defined at the beginning of the stored procedure. 此
@Availability
变量是我在存储过程开始时定义的输入。
An IN clause will work nicely here as it will work for both single values and a comma-separated list of values.. IN子句在这里可以很好地工作,因为它既可以用于单个值,也可以用于逗号分隔的值列表。
CREATE PROC YourProcName (@Availability int) AS declare @sql nvarchar(MAX) Declare @availabilityStatus nvarchar(MAX) BEGIN IF @Availability = 1 set @availabilityStatus = '0, 1, 2' ELSE set @availabilityStatus = '1' set @sql = 'SELECT Distinct P.ProductId, P.BrandId, P.[' + @OrderIndex + '] FROM Products P INNER JOIN ProductStores PS ON P.ProductId = PS.ProductId ' + 'Where PS.StoreId = @StoreId and PS.Status IN (' + @availabilityStatus + ') or PS.AvailabilityRank < ' -- the rest of your @sql code -- the rest of your code END GO
您是否尝试添加方括号,例如(@Availability = 1)
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.