Moji
Moji

Reputation: 1830

SQL Server Stored Procedure syntax error when adding several OR clauses

I am trying to select some products from products table using a stored procedure in SQL Server 2016 but when I am adding several or clause it gives me this syntax error:

Msg 102, Level 15, State 1, Line 5 Incorrect syntax near '100'.

here is the line of stored procedure that when I add it, it gives me the error. (without this line, it is ok):

@StoreId int = null,
//the code is quite verbose and I added storeid variable as a clarification here 
//and in the actual code it is defined in the proper line(not here) and the part 
//that is creating the error is the below part cause I have tested it and When I 
//remove it, it performs ok
IF @ShowUnavailable = 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.StoreId != @StoreId and PS.Status IN(0,2))'

Upvotes: 0

Views: 330

Answers (3)

p.k
p.k

Reputation: 71

In

'Where  PS.StoreId = **@StoreId** and (PS.Status  IN (' + @availabilityStatus + ') or (PS.StoreId != **@StoreId** and PS.Status IN(0,2))'

the way you have passed @StoreId is seems to be some thing wrong.

please use proper cast or conversion of nvarchar to int if needed.

Upvotes: 1

Gen Wan
Gen Wan

Reputation: 2009

1, If the variable is an integer, you need to convert it to varchar. Because @sql is a string.

2, Please clarify the data type of @availabilityStatus. I used '1,2' as the sample.

declare @StoreID int = 0
declare @OrderIndex int = 0
declare @availabilityStatus varchar(max) = '1,2'
declare @sql nvarchar(max)
set @sql = 
            'SELECT Distinct P.ProductId, P.BrandId, P.[' + cast(@OrderIndex as varchar(100)) + '] FROM Products P INNER JOIN ProductStores PS ON P.ProductId = PS.ProductId ' +
            'Where PS.StoreId = '+ cast(@StoreId as varchar(100))+ ' and (PS.Status  IN (' + @availabilityStatus + ') or (PS.StoreId != '+cast(@StoreId as varchar(100))+' and PS.Status IN(0,2))'

Print @sql

Test Result: DB <> Fiddle

Upvotes: 1

Deepshikha
Deepshikha

Reputation: 10264

To me it seems like @OrderIndex is of datatype INT and while string concatenation an Implicit conversion is happening creating the error. Try converting @OrderIndex as cast (@OrderIndex as varchar) to resolve the error `[Conversion failed when converting the nvarchar value ...to data type int.]

Edit: If above is not the case and error is coming not while code compilation but while executing the dynamic sql @sql string then explicitly convert int datatype to varchar for string concatenation as cast (@StoreID as varchar).

Upvotes: 1

Related Questions