【问题标题】:Pass in Dynamic number of parameters to a stored procedure将动态数量的参数传递给存储过程
【发布时间】:2011-07-16 17:38:11
【问题描述】:

我的 .NET 应用程序中有一个函数,它需要搜索未知数量的参数。

例如:select * from tbl where x=1 or x=2 or x=3 or x=4

是否可以在 .NET 和 SQL 中执行?我如何在 .NET 中创建动态参数(我想用循环来做)但是我如何在我的存储过程中声明它们? sql有数组吗?

请帮忙。

谢谢!

【问题讨论】:

  • 什么样的数据库?微软 SQL? 2005 年? 2008 年?甲骨文? MySQL?

标签: .net sql sql-server sql-server-2005 stored-procedures


【解决方案1】:

您可能想查看表值参数(SQL Server 2008 及更高版本):

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

【讨论】:

    【解决方案2】:

    您可以传入逗号分隔的列表,使用表函数将其拆分为表,然后使用 IN 子句。 This article 继续这样做。

    表函数:

    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
    

    那么你的存储过程可以做到这一点:

    SELECT *
    FROM tbl 
    WHERE id IN (
                SELECT Value
                FROM funcListToTableInt(@ids,',')
                       )
    

    【讨论】:

    【解决方案3】:

    尝试传入一个 XML 列表作为参数,然后您可以使用光标或类似的东西来处理 XML 列表中的项目

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      相关资源
      最近更新 更多