2016-05-12 59 views
0

我想將來自不同SQL Server存儲過程(每個都返回1個結果集)的數據集填充到數據集內自己的數據表中。將具有不同SQL Server存儲過程的相同數據集填充到數據表中

我真的不想傳遞SQL作爲文本「exec sp1; exec sp2」...我想使用下面的cmd.CommandType = CommandType.StoredProcedure方法,這樣做的最好方法是什麼?

清除SqlDataAdapter並再次調用它以加載sp2結果集?它會消滅表(0)嗎?我想它來填充表(1)

cnn.Open() 
cmdSQL1 = New SqlCommand 
cmdSQL1.Connection = cnn 
cmdSQL1.CommandType = CommandType.StoredProcedure 
cmdSQL1.CommandText = ("sp1") 
cmdSQL2 = New SqlCommand 
cmdSQL2.Connection = cnn 
cmdSQL2.CommandType = CommandType.StoredProcedure 
cmdSQL2.CommandText = ("sp2") 

Dim da As New SqlDataAdapter(cmdSQL1) 
da.Fill(ds) 

編輯

da.Dispose() 
da.SelectCommand = cmdSQL2 
da.Fill(ds, "tab2") 

dt = ds.Tables(0) 
dt2 = ds.Tables(1) 
+0

爲什麼不試試看並找出答案?設置一個斷點並在代碼完成時查看'ds'中的表的數量。 'DataAdapter.Fill()'方法被重載。 'Fill(ds,string)'可以讓你創建並命名目標表。 – Plutonix

+0

* *代碼*只填充sp1/cmdSQL1中的一個表(表(0));第二個是從來沒有使用過。我認爲「......」意味着你也爲另一個做了同樣的事情。 – Plutonix

+0

那麼有沒有辦法填充下一個表,而不必像我做「tab2」那樣命名它,有沒有像nextresult()那樣的東西?還是我以錯誤的方式接近? –

回答

0

保持簡單。看看這個例子。

Dim ds As New Data.DataSet() ' Dataset to fill 
Using cnn As New Data.SqlClient.SqlConnection("my connection string") 
    Dim cmd As New Data.SqlClient.SqlCommand("sp1", cnn) ' The only command 
    cmd.CommandType = Data.CommandType.StoredProcedure 
    cmd.Parameters.Add(New Data.SqlClient.SqlParameter("@id", Data.DbType.Int32)).Value = 1234 ' parameters if we need some 
    Dim dt As New Data.DataTable() 
    cnn.Open() 
    dt.Load(cmd.ExecuteReader()) ' load dt from reader. DataAdapter in fact does the same 
    ds.Tables.Add(dt) ' 0th tbl added 
    cmd.CommandText = "sp2" ' prepare 2nd SP 
    cmd.Parameters.Clear() ' no comment 
    dt = New Data.DataTable() ' recreate dt 
    dt.Load(cmd.ExecuteReader()) 
    ds.Tables.Add(dt) ' 1st tbl added 
    cnn.Close() ' clean up your place 
    cmd.Dispose() ' clean up your place 
End Using