【问题标题】:How to run a Stored Procedure which returns a dataset如何运行返回数据集的存储过程
【发布时间】:2013-07-13 12:11:32
【问题描述】:

我有一个简单的存储过程(从 MyTable 中选择名称、ID),我想从 C#(或 VB.NET)调用它来填充数据集。

这是我的代码:

Public Class PaymentDataAccess

    Public Function GetPaymentData() As DataSet

        Dim cn As New SqlClient.SqlConnection
        cn.ConnectionString = "Data Source=WORK-HP\BTFSERVER1;Initial Catalog=PaymentReminder;Integrated Security=True"

        Dim Cmd As New SqlCommand("GetPaymentData", cn)

        Cmd.CommandType = CommandType.StoredProcedure

        Dim sa As New SqlDataAdapter(Cmd)

        cn.Open()

        Dim ds As DataSet = Nothing
        Try

            sa.Fill(ds)

        Catch ex As Exception
            Dim i As Integer = 7
        End Try
        Return ds

    End Function


End Class

我在sa.Fill(ds) 遇到异常

{"Value cannot be null.
Parameter name: dataSet"}
    System.ArgumentNullException: {"Value cannot be null.
Parameter name: dataSet"}

这是我的存储过程:

USE [PaymentReminder]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetPaymentData] 

AS
BEGIN

    SET NOCOUNT ON;   
    SELECT * from Payments
END

【问题讨论】:

    标签: sql-server vb.net


    【解决方案1】:

    只需更改此行

     Dim ds As DataSet = Nothing
    

     Dim ds = new DataSet()
    

    您需要将初始化的 DataSet 传递给 SqlDataAdapter.Fill 方法。
    其实你的代码就像

     sa.Fill(Nothing) 
    

    当然,Fill 代码并不认可这一点。

    【讨论】:

    • 我不同意我的代码就像 sa.Fill(Nothing) 声明。我仍在将数据集传递给 dataadapter,它的初始值什么都没有。
    • 感谢您的快速回复。
    • @JoeTatavaran:关于您的第二条评论,这是 ByValByRef 参数之间的区别。 SqlDataAdapter.Fill(DataSet) 接受 ByVal 参数。也就是说,您没有传递变量ds,其值可以通过该方法从Nothing 更改为DataSet 实例;您正在传递变量的值 (Nothing),并且该方法无法更改您的 ds 变量。
    • Joe,您应该将 reference 传递给 DataSet,这意味着适合包含 DataSet 的内存区域,但是您将 DataSet 引用设置为 Nothing 并传递此值作为参考
    猜你喜欢
    • 2016-08-19
    • 2011-02-17
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多