2013-05-21 47 views
0

我的存储过程是:将当如何字符串传递给存储过程

ALTER Proc [hometution].[Sp_GetHomePageProducts] 
    @CatIds nvarchar(500) 
as 
begin 
    Select Top 3 * 
    from Product p 
    where p.Id in 
     (Select ProductId 
     from Product_Category_Mapping PCM 
     where PCM.CategoryId in (@CatIds)) 
     and p.ShowOnHomePage=1 
     and p.Deleted=0 
    order by UpdatedOnUtc 
end 

我打电话像这样

exec Sp_GetHomePageProducts @CatIds='17,12' 

我收到错误

转换失败nvarchar值'17,12'为数据类型int。

+2

使用一个(https://www.google.com/search?q=sqlserver+split+function)把你的参数成多行 – Andomar

回答

2

尝试这一个 - 的许多[分割功能]

ALTER PROC [hometution].[Sp_GetHomePageProducts] 

@CatIds NVARCHAR(500) 

AS 
BEGIN 

    ;WITH cte AS 
    (
     SELECT id = p.value('(./s)[1]', 'INT') 
     FROM (
      SELECT field = CAST('<r><s>' + REPLACE(@CatIds, ',', '</s></r><r><s>') + '</s></r>' AS XML) 
     ) d 
     CROSS APPLY field.nodes('/r') t(p) 
    ) 
    SELECT TOP 3 * 
    FROM dbo.product p 
    WHERE p.id IN (
      SELECT PCM.ProductId 
      FROM dbo.Product_Category_Mapping PCM 
      JOIN cte c ON c.id = PCM.CategoryId 
     ) 
     AND p.ShowOnHomePage = 1 
     AND p.Deleted = 0 
    ORDER BY UpdatedOnUtc 

END 
+0

由于其工作正常:) –

+0

不客气@Avinash辛格。 – Devart

相关问题