How to parse a VARCHAR passed to a stored procedure in SQL Server?

后端 未结 2 1363
孤城傲影
孤城傲影 2020-12-11 13:17

I have two tables tbl_Products and tbl_Brands, both are joined on BrandId.

I have a stored procedure which should return all t

2条回答
  •  长情又很酷
    2020-12-11 13:57

    If possible, don't use varchar for this kind of things, use a table valued parameter instead.

    To use a tabled value parameter you should first declare a user defined table type:

    CREATE TYPE IntList As Table
    (
        IntValue int
    )
    

    Then change your stored procedure to accept this variable instead of the nvarchar:

    create proc Sp_ReturnPrdoucts
        @BrandIds dbo.IntList readonly -- Note: readonly is a must!
    AS
    BEGIN
    
    SELECT * 
    FROM tbl_Products as p 
    join tbl_Brands b on p.ProductBrandId=b.BrandId 
    join @BrandIds ON(b.BrandId = IntValue)
    
    END
    

    The problem is that the IN() operator expects a list of variables separated by commas, while you provide a single variable that it's value is a comma separated string.

    If you can't use a table valued parameter, you can use a string spliting function in sql to convert the value of the varchar to a table of ints. there are many splitters out there, I would recommend reading this article before picking one.

提交回复
热议问题