10

我有一个带有以下控件的aspx 页面: TextBox、CheckBoxList、DropDownList。它们用于指定搜索条件。这些记录是使用存储过程从SQL Server 数据库中获取的。

  1. CheckBoxList中的每个CheckBox都有一个值,该值是数据库中产品组的实际 ID。如果选中了多个复选框,如何将 ID 列表作为一组传递给存储过程,以便我可以使用IN @IdList?我应该在 C# 和 T-SQL 中使用哪些变量类型?有可能吗?

  2. DropDownList的第一项是“ALL”。选择“ALL”时,我需要将NULL之类的内容传递给存储过程。如果参数为NULL,如何使存储过程忽略参数?

    CREATE PROCEDURE FilterList @ProductName nvarchar(200), @ProductGroupID int AS BEGIN SELECT prod_id AS 'ID', prod_name AS 'Name' FROM dbo.Products WHERE prod_group_id = @ProductGroupID OR prod_name = @ProductName END

4

2 回答 2

11

您可以通过使默认值等于 NULL 来实现 T-SQL 存储过程中的可选参数。

将 NULL 用作“忽略此参数”的示例:

CREATE PROCEDURE [dbo].[dcspFilterEmpList]
    @ProductName nvarchar(200) = null,
    @ProductGroupID int = null
AS BEGIN 

    SELECT
    prod_id AS 'ID',
    prod_name AS 'Name'
    FROM dbo.Products

    WHERE (prod_group_id = @ProductGroupID OR @ProductGroupID IS NULL)
    AND (prod_name = @ProductName OR @ProductName IS NULL)

END

It's perfectly fine to define a stored procedure to take a table-valued parameter in T-SQL. Here is an article on the subject http://sqlwithmanoj.wordpress.com/2012/09/10/passing-multipledynamic-values-to-stored-procedures-functions-part4-by-using-tvp/

If you need more info on this google for "table-valued parameter"

Example using multi-valued parameters:

CREATE TYPE XTV_ProductNames AS TABLE  --extension, table valued == XTV
( ProductName nvarchar(50))
GO
CREATE TYPE XTV_ProductGroups AS TABLE  --extension, table valued == XTV
( ProductGroupID int))
GO
CREATE PROCEDURE [dbo].[dcspFilterEmpList]
    @TVP1 XTV_ProductNames READONLY
    ,@TVP2 XTV_ProductGroups READONLY
AS BEGIN 
    SELECT
    prod_id AS 'ID',
    prod_name AS 'Name'
    FROM dbo.Products as p
    INNER JOIN @TVP1 as s
        ON p.prod_name = s.ProductName
    UNION
    SELECT
    prod_id AS 'ID',
    prod_name AS 'Name'
    FROM dbo.Products as p
    INNER JOIN @TVP2 as s
        ON p.prod_group_id = s.ProductGroupID
END
于 2013-04-23T13:18:35.750 回答
8

Your answer was correct David, but it was a little misleading because the parameter equaling NULL does not make it optional; it just has to be set to any value period. This also creates optional parameters:

CREATE PROCEDURE [dbo].[dcspFilterEmpList]
    @ProductName nvarchar(200) = 'DefaultProduct',
    @ProductGroupID int = 1
AS

Which could thus be executed without passing any parameters, i.e.:

EXEC [dbo].[dcspFilterEmpList]

I understand that this wasn't necessarily what Piscovetz was trying to do, but it seems to match more closely the actual topic question shown, and it is an important distinction.

于 2014-08-22T21:17:04.227 回答