标量函数的单个参数中的多个值

时间:2013-12-11 21:02:05

标签: sql sql-server parameters filtering user-defined-functions

有没有办法在SQL Server 2008 R2中的标量值函数的单个参数中输入多个值,并让它使用这两个值按该参数过滤数据?

例如,我想做以下

    SET @Salesperson='BILL' OR 'MOSES'

    SELECT Sum(SalesDollars)
    FROM Invoices
    WHERE Invoices.Salesperson = @Salesperson

我试图使用以下作为WHERE子句,但这也没有用。

    SET @Salesperson='BILL','MOSES'

    SELECT Sum(SalesDollars)
    FROM Invoices
    WHERE Invoices.Salesperson IN (@Salesperson)

如果我处理整数而不是varchar值会更容易吗?

任何帮助都绝对值得赞赏!

3 个答案:

答案 0 :(得分:3)

您需要使用表值参数。在technetmsdn

上查找

最重要的是,您的表值参数可以包含多个列。

但请注意,您必须将TVP参数定义为只读。因此,如果您想从函数中返回类似的集合,则需要在函数内部创建另一个变量。

示例:

  CREATE TYPE Names AS TABLE 
  ( Name VARCHAR(50));
  GO

  /* Create a procedure to receive data for the table-valued parameter. */
  CREATE PROCEDURE dbo.mySP
      @n Names READONLY
      AS 
      SELECT Sum(SalesDollars)
      FROM 
      WHERE Invoices.Salesperson in (select Name from @n)
  GO

  CREATE FUNCTION dbo.myFun(@n Names READONLY) returns int
      AS
      SELECT Sum(SalesDollars)
      FROM 
      WHERE Invoices.Salesperson in (select Name from @n)
  GO

  /* Declare a variable that references the type. */
  DECLARE @names AS Names;

  /* Add data to the table variable. */
  INSERT INTO @names (Name)
  VALUES ('BILL'),('MOSES')

  -- using stored procedure with TVP
  EXEC dbo.mySP @names

  -- using function with TVP
  select dbo.myFun(@names)
  GO

答案 1 :(得分:0)

这可以这样做:

SET @Salesperson='BILL,MOSES'

SELECT *
FROM YourTable
WHERE Invoices.Salesperson IN (SELECT * FROM dbo.split(@Salesperson,','))

This is how您将价值分开。

答案 2 :(得分:0)

我通常会使用用户定义的表类型执行此操作:SQL Fiddle Example

CREATE TYPE <schema>.SalespersonList AS TABLE
(
   Name varchar(32)
)

您可能必须为类型授予执行权限:

GRANT EXECUTE ON TYPE::<schema>.SalespersonList TO <user> 

然后你可以创建一个使用它的函数:

CREATE FUNCTION <schema>.fnGetTotalSales
(
    @nameList <schema>.SalespersonList READONLY
)
RETURNS INT
AS
BEGIN 
    DECLARE @ret INT

    SELECT @ret = Sum(SalesDollars)
    FROM Invoices i
    INNER JOIN @nameList nl ON nl.Name = i.Salesperson

    RETURN @ret
END 

然后你只需将列表插入到类型中并调用函数:

DECLARE @salesPersonList <schema>.SalespersonList 

INSERT INTO @salesPersonList (Name)
SELECT 'Bill'
UNION 
SELECT 'Moses'

SELECT <schema>.fnGetTotalSales(@salesPersonList)