如何将字符串传递给存储过程

时间:2013-05-21 09:59:09

标签: sql-server stored-procedures

我的存储过程是:

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时,转换失败。

1 个答案:

答案 0 :(得分: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