0

我正在编写 SSRS2005 中的报告,我需要使用一些 VB.NET 代码来访问与报告中的数据库不同的数据库并返回整数列表(用户 ID)。我需要使用一些 VB.NET 代码来执行此操作。我有一些“有效”的代码,因为它不会引发任何错误并且我得到返回的值。但是,我只得到第一个值而不是整个列表。这是我到目前为止所拥有的:

Public Function GetUsers(ByVal param As Integer) As String
Dim sqlCon As New System.Data.SqlClient.SqlConnection 
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dRet As String
Dim sCmdText As String

sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"


cmd = New System.Data.SqlClient.SqlCommand
sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users(" 
'cmd.CommandType = CommandType.Text
cmd.Connection = sqlCon
cmd.CommandTimeout = 0

sCmdText = sCmdText & param
sCmdText = sCmdText & ")"

cmd.CommandText = sCmdText
If sqlCon.State <> System.Data.ConnectionState.Open Then
sqlCon.Open()
End If
dRet = cmd.ExecuteScalar() & ""     
sqlCon.Close()

Return dRet

End Function

我尝试过使用 DataSet 数据类型,但我收到错误消息,无法将 DataSet 转换为字符串。

有什么想法我需要做些什么才能让它发挥作用?

4

1 回答 1

0

将您的代码修改为以下

Public Function GetUsers(ByVal param As Integer) As String
'
Dim sqlCon As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dtAdapter As Data.SqlClient.SqlDataReader
Dim dRet As String
Dim sCmdText As String
'
  'connection
  sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"
  sqlCon.Open()
  '
  'query
  sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users(" & param & ")"
  '
  'command
  cmd = New System.Data.SqlClient.SqlCommand(sCmdText, sqlCon)
  cmd.CommandTimeout = 0
  '
  'main course
  If cmd.Connection.State = Data.ConnectionState.Closed Then cmd.Connection.Open()
  dtAdapter = cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
  If dtAdapter.HasRows Then
    While dtAdapter.Read()
      ' following assumes "dbUserId" is the userid field in the database 
      ' also use pipe "|" to split the userid's whens theres more than one
      ' this is so you can still use STRING as the function return and not an ARRAY
      dRet = dRet & dtAdapter.GetValue(dtAdapter.GetOrdinal("dbUserId")) & "|"
    End While
  End If
  If cmd.Connection.State <> Data.ConnectionState.Closed Then cmd.Connection.Close()
  Return dRet
  '
End Function
于 2013-04-01T20:36:46.173 回答