如何使用逗号运算符在SQL中添加多个值

时间:2016-12-15 06:57:48

标签: sql-server-2008

alter Procedure sp_range_chkbox       
    @Price int,        
    @Price1 int,      
    @chkValue varchar(max)  
as        
begin        
    IF (@chkValue > 0)        
    begin        
        select 
            ProductID, ProductName, ProductImage, ProductPrice 
        from 
            tblProddetails 
        where 
           (ProductPrice between @Price and @Price1) 
           and (CHARINDEX(',' + CAST(Categoryid as VARCHAR(8000)) + ',', ',' + @chkvalue + ',') > 0)    
    end        
    else        
    begin        
        select 
            ProductID, ProductName, ProductImage, ProductPrice 
        from  
            tblProddetails 
        where 
            ProductPrice between @Price and @Price1          
    end        
end

我将@chkvalue用作Varchar(max)

但代码会抛出错误:

  

将varchar值'3,1'转换为数据类型int

时转换失败

2 个答案:

答案 0 :(得分:0)

此检查是问题..

IF (@chkValue > 0)

由于显而易见的原因,SQL Server尝试将@chkValue转换为整数,该整数的类型为varchar(max)。您传递给@chkValue的值(通过查看错误消息必须为'3,1')无法转换为整数。

答案 1 :(得分:0)

IF (@chkValue > 0)更改为IF(LEN(@chkValue)>0)

alter Procedure sp_range_chkbox       
    @Price int,        
    @Price1 int,      
    @chkValue varchar(max)  
as        
begin        
    IF(LEN(@chkValue)>0)       
    begin        
        select 
            ProductID, ProductName, ProductImage, ProductPrice 
        from 
            tblProddetails 
        where 
           (ProductPrice between @Price and @Price1) 
           and (CHARINDEX(',' + CAST(Categoryid as VARCHAR(8000)) + ',', ',' + @chkvalue + ',') > 0)    
    end        
    else        
    begin        
        select 
            ProductID, ProductName, ProductImage, ProductPrice 
        from  
            tblProddetails 
        where 
            ProductPrice between @Price and @Price1          
    end        
end