如何在代码中获取sql的输出参数

时间:2009-08-21 09:12:50

标签: asp.net vb.net

我的存储过程是这样的。

 ALTER PROCEDURE [dbo].[GetImagesByDesignId] 
        @DesignID bigint,
        @RegID bigint,
        @PageIndex INT,
        @NumRows INT,
        @ImageCount INT OUTPUT
    AS

BEGIN

    SELECT @ImageCount=(SELECT COUNT(*) FROM DocManagement where DesignID=@DesignID and RegID=@RegID)

    Declare @startRowIndex INT;
    set @startRowIndex = (@PageIndex * @NumRows) + 1;

    With ImageEntries as (
        SELECT ROW_NUMBER() OVER (ORDER BY DocumentID ASC) as Row, RegID, DesignID,ImageName
        FROM DocManagement
        WHERE  DesignID=@DesignID and RegID=@RegID
    )

    Select RegID, DesignID,ImageName
    FROM ImageEntries
    WHERE Row between 
    @startRowIndex and @StartRowIndex+@NumRows-1

END

我在我的代码隐藏中调用storedprocedure

Dim dt As DataTable = objUpload.GetDocuments(lngRegID, lngDesignID)
            dlView.DataSource = dt
            dlView.DataBind()

dlView是datalist.Method GetDocuments是用另一个类写的

Public Function GetDocuments(ByVal lngRegID As Long, ByVal lngDesID As Long) As DataTable
            Try

                Dim db As Database = DatabaseFactory.CreateDatabase()
                Dim DbCommand As DbCommand = db.GetStoredProcCommand("GetImagesByDesignId")
                db.AddInParameter(DbCommand, "@RegID", DbType.Int64, lngRegID)
                db.AddInParameter(DbCommand, "@DesignID", DbType.Int64, lngDesID)
                db.AddInParameter(DbCommand, "@PageIndex ", DbType.Int32, intPageIndex)
                db.AddInParameter(DbCommand, "@NumRows ", DbType.Int32, intNumRows)
                db.AddOutParameter(DbCommand, "ImageCount", DbType.Int32, 250)
                Return db.ExecuteDataSet(DbCommand).Tables(0)
                Dim strOutput() As String = {db.GetParameterValue(DbCommand, "ImageCount").ToString}

            Catch ex As Exception
            End Try

        End Function

问题是我想获得datattable以及codebehind中的imagecount。我如何将datatable和imagecount返回给codebehind.Can任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

您可以创建一个要使用的类,它包含数据表和图像计数。或者您可以通过引用发送变量作为参数:

Public Function GetDocuments(ByVal regID As Long, ByVal desID As Long, ByRef imageCount As Integer) As DataTable

在方法中,您只需设置imageCount的值。

在存储过程中,您不需要嵌套查询来获取计数。就这样做:

select @ImageCount = count(*)
from DocManagement
where DesignID = @DesignID and RegID = @RegID

注意:
我看到你有Catch块没有任何内容。 永远不会这样做。您正在捕捉异常并忽略它们,这只会导致问题。

在极少数情况下,您实际上需要捕获异常并忽略它,您至少应该在Catch块中有一条注释来解释它被忽略的原因。

此外,当您应该捕获更具体的类Exception时,您正在捕获基类SqlException

答案 1 :(得分:1)

Public Function GetDocuments(ByVal lngRegID As Long, ByVal lngDesID As Long, ByRef strOutput As String) As DataTable

您可以使用ByRef并传递字符串变量作为参考,并在您的方法中进行设置。 strOutput的引用将传递给您的方法,当您在方法中设置该变量的值时,您可以在方法调用后返回更改的值。

Dim strOutput As String = Nothing
Dim dt As DataTable = GetDocuments(lngRegID, lngDesID, strOutput)
Console.WriteLine(strOutput)