Pass in Dynamic number of parameters to a stored p

2019-08-29 05:59发布

I have a function in my .NET application, that needs to do a search of an unknown number of parameters.

for example: select * from tbl where x=1 or x=2 or x=3 or x=4

is it possible to do in .NEt and SQL? how do i go about creating dynamic parameters in .NET (I was thinking doing it with a loop) but then how do i declare them in my stored procedure? does sql have arrays?

please help.

thank you!

3条回答
何必那么认真
2楼-- · 2019-08-29 06:20

You might want to look at table-valued parameters (SQL Server 2008 and up):

http://msdn.microsoft.com/en-us/library/bb510489.aspx

查看更多
小情绪 Triste *
3楼-- · 2019-08-29 06:21

You can pass in a comma seperated list, use a table function to split that out into a table and then use an IN clause. This article goes over doing that.

table function:

CREATE FUNCTION dbo.funcListToTableInt(@list as varchar(8000), @delim as varchar(10))
RETURNS @listTable table(
  Value INT
  )
AS
BEGIN
    --Declare helper to identify the position of the delim
    DECLARE @DelimPosition INT

    --Prime the loop, with an initial check for the delim
    SET @DelimPosition = CHARINDEX(@delim, @list)

    --Loop through, until we no longer find the delimiter
    WHILE @DelimPosition > 0
    BEGIN
        --Add the item to the table
        INSERT INTO @listTable(Value)
            VALUES(CAST(RTRIM(LEFT(@list, @DelimPosition - 1)) AS INT))

        --Remove the entry from the List
        SET @list = right(@list, len(@list) - @DelimPosition)

        --Perform position comparison
        SET @DelimPosition = CHARINDEX(@delim, @list)
    END

    --If we still have an entry, add it to the list
    IF len(@list) > 0
        insert into @listTable(Value)
        values(CAST(RTRIM(@list) AS INT))

  RETURN
END
GO

Then your stored proc can do this:

SELECT *
FROM tbl 
WHERE id IN (
            SELECT Value
            FROM funcListToTableInt(@ids,',')
                   )
查看更多
聊天终结者
4楼-- · 2019-08-29 06:34

Try passing in an XML list as the parameter, then you can work through the items in the XML list with a cursor or something similar

查看更多
登录 后发表回答