将null参数发送到查询字符串存储过程

时间:2013-07-11 15:06:32

标签: c# asp.net stored-procedures sql-server-2012-express

我有以下问题。我想使用querystringparameter将空值发送到存储过程。

这是我的存储过程

CREATE PROCEDURE spGetAllProducts
 @catID int = null,
 @subcatID int = null
AS
BEGIN
    SELECT * FROM Products WHERE
    ((@catID is null) OR (category_id = @catID))
    AND ((@subcatID is null) OR (subcategory_id = @subcatID))
END

当我按照我想要的方式测试以下查询时,它正在工作

spGetAllProducts null, '3'
spGetAllProducts '8', null
spGetAllProducts '8', '3'
spGetAllProducts null, null

但是当我尝试使用queryparameter发送空值时,它无法正常工作

这是我的sqldatasource

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringReviewDB %>" SelectCommandType="StoredProcedure" SelectCommand="spGetAllProducts">

    <SelectParameters>
    <asp:QueryStringParameter Direction="Input" Name="catID" QueryStringField="catID" Type="Int32" />
    <asp:QueryStringParameter Direction="Input" Name="subcatID" QueryStringField="subcatID" Type="Int32" DefaultValue="" ConvertEmptyStringToNull="True" />
    </SelectParameters>

    </asp:SqlDataSource>

当我发送这样的查询时

http://localhost:50693/TreeViews.aspx?catID=8&subcatID=3

它正在工作但是当我发送以下查询时它无法正常工作

http://localhost:50693/TreeViews.aspx?catID=8&subcatID=

从现在开始

1 个答案:

答案 0 :(得分:0)

试试这个

CREATE PROCEDURE spGetAllProducts @catID int = null, @subcatID int = null AS BEGIN SELECT * FROM Products WHERE ((@catID '') OR (category_id = @catID)) AND ((@subcatID = '') OR (subcategory_id = @subcatID)) END

我认为存储过程将其作为空字符串而不是null,我遇到了类似的问题,它对我有用