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

后端 未结 2 1355
孤城傲影
孤城傲影 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:44

    Another alternative is to use 'indirection' (as I've always called it)

    You can then do..

    create proc Sp_ReturnPrdoucts
    @BrandIds varchar(500) = '6,7,8'
    AS
    BEGIN
        if (isnumeric(replace(@BrandIds,',',''))=1) 
        begin
            exec('SELECT * FROM tbl_Products as p join tbl_Brands b on p.ProductBrandId=b.BrandId WHERE b.BrandId IN ('+@BrandIds+')')
        end
    END
    

    This way the select statement is built as a string, then executed.

    I've now added validation to ensure that the string being passed in is purely numeric (after removing all the commas)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题