2013-04-01 96 views
0

我正在使用SSRS2005中的一個報告,在那裏我需要使用一些VB.NET代碼發送到與報告中不同的數據庫,並返回整數列表(用戶ID)。我需要使用一些VB.NET代碼來做到這一點。我有一些「有效」的代碼,它不會拋出任何錯誤,並且我返回值。但是,我只獲得第一個值,而不是整個列表。以下是我迄今爲止:如何使用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作爲字符串的錯誤消息。

任何想法,我需要做的,以使其發揮作用?

+1

'ExecuteScalar'始終只返回一個值。這就是「標量」的含義。看看http://www.mindfiresolutions.com/Forming-Comma-Separated-String-in-SQL-Server-428.php –

+0

如果你使用ExecuteScalar它只會返回一個值,請試用帶有DataSet或DataReader的SqlDataAdapter –

+0

謝謝羅伯特。就是這樣。它現在有效。 –

回答

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