DataSource存储过程奇怪的行为

时间:2014-08-04 18:45:08

标签: c# sql asp.net sql-server

我有一个名为ItemGetCategoriesSqlDataSource

的存储过程
<asp:SqlDataSource ID="CategoriesDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
     SelectCommand="ItemGetCategories" SelectCommandType="StoredProcedure" OnSelected="CategoriesDataSource_Selected">
       <SelectParameters>
          <asp:RouteParameter Name="StockItemId" RouteKey="id" Type="String" />                                            
        </SelectParameters>
</asp:SqlDataSource>

SQL Server正在从数据源接收此查询

exec ItemGetCategories @StockItemId=15

并且没有任何内容返回到数据源,在SQL Server Management Studio中执行此查询也不会返回任何行。

现在奇怪的是,从SQL Server Management Studio执行此操作会返回1行。

USE [MyDB]
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[ItemGetCategories]
        @StockItemId = N'15'

SELECT  'Return Value' = @return_value
GO

这是存储过程

ALTER PROCEDURE [dbo].[ItemGetCategories]
    @StockItemId nvarchar(10) = '1'
AS
BEGIN
    SET NOCOUNT ON;

    WITH categoryPath(Id,Slug,CategoryName)
    AS
    (
        SELECT 
           Id, Slug, CategoryName 
        FROM 
           Categories
        WHERE 
           ParentCategoryId IS NULL

        UNION ALL

        SELECT 
            Categories.Id,
            CAST(categoryPath.Slug + '/' + categories.Slug AS NVARCHAR(150)),
            Categories.CategoryName
        FROM 
            Categories
        JOIN 
            categoryPath ON Categories.ParentCategoryId = categoryPath.Id
     )
     SELECT * 
     FROM [ItemCategories]
     JOIN categoryPath ON [ItemCategories].StockId = categoryPath.Id 
     WHERE [ItemCategories].StockId = @StockItemId
END

为什么存储过程不会将任何行返回到数据源?

我试图将存储过程参数从int更改为string,并将参数从datasource传递为字符串,但仍然是相同的结果。

1 个答案:

答案 0 :(得分:1)

除了数据类型不匹配外,您的过程代码没有任何问题。对以下几点进行更改。

将过程参数@StockItemId更改为INT,因为[ItemCategories].StockIdINT类型,并且您正在根据它进行过滤WHERE [ItemCategories].StockId=@StockItemId

ALTER PROCEDURE [dbo].[ItemGetCategories]
    @StockItemId INT = NULL 

相应地定义数据源属性,如

<SelectParameters>
<asp:RouteParameter Name="StockItemId" RouteKey="id" Type="INT32" />                                            
</SelectParameters>