1

的x個我通常做調用SQL存儲過程和使用VBA在Excel中顯示的數據是:Visual Studio的VBA Excel中添加從存儲過程中獲取數據的列

Dim sqlConnection1 As New SqlConnection("Data Source=[INSTANCE];Initial Catalog=[databasename];User ID=[user];Password=[password];") 
     Dim shXL As Excel.Worksheet 
     shXL = Globals.ThisAddIn.Application.ActiveSheet 
     Dim Str2 As New SqlCommand 
     Dim reader As SqlDataReader 
     Dim j As Integer 

     Str2.CommandText = "[NAME OF PROCEDURE]" 
     Str2.Connection = sqlConnection1 
     Str2.CommandType = CommandType.StoredProcedure 
     reader = Str2.ExecuteReader() 
     j = 2 
     While reader.Read() 
      shXL.Cells(5, j).Value = reader("[NAME OF COLUMN]") 
      j = j +1 
     End While 

     sqlConnection1.Close() 

它的工作原理,當返回的列數不變時。

但我有一個存儲過程比返回x列數,所以代碼必須找出有多少列我的存儲過程返回並相應地顯示數據。

回答

0

正常情況下;)SqlDataReader已得到FieldCount property,它返回當前行中的列數。

另一種方法是使用Data.Datatable這可能是有用的你的情況。

Dim dt As Data.DataTable = new Data.DataTable() 
dt.Load(reader) 
Dim cc As Integer = dt.Columns.Cont 'get the count of columns 
Dim rc As Integer = dt.Rows.Count 'get the count of rows 
For c = 0 to cc 
    For r =0 to rc 
     'here extract your data ;) 
    Next 
Next 
相關問題