EXCEL vbaでwhereのnoをIN+配列+joinで複数指定して、SQLを1回で済ませると手っ取り早いが、SQL文の最大文字数(バッチサイズ)65536バイト以内にする必要がある。 そこで、noをひとつ指定したSELECT を必要な分だけ繰り返し発行する。 ActiveWorkbook.Worksheets(1)のA列にNOが入っていると仮定する。これでどうじゃろかな?
Dim i As Long Dim noStr as String Dim strSQL as String Dim maxRow as Long Dim cn As New ADODB.Connection Dim rs As New ADODB.Recordset Private Const PROVIDER As String = "SQLOLEDB" Private Const DATA_SOURCE As String = "localhost" 'サーバ名 Private Const DATABASE As String = "dbname" 'データベース名 Private Const USER_ID As String = "UID=user" 'ユーザID Private Const PASSWORD As String = "password" 'ユーザパスワード 'SQL Server認証で接続する場合 cn.ConnectionString = "Provider=" & PROVIDER _ & ";Data Source=" & DATA_SOURCE _ & ";Initial Catalog=" & DATABASE _ & ";UID=" & USER_ID _ & ";PWD=" & PASSWORD cn.Open maxRow = ActiveWorkbook.Worksheets(1).Cells(Rows.Count,1).End(xlUp).Row For i = 2 to maxRow nostr = activeWorkbook.WorkSheet(1).Cells(i,1).Value strSQL = SELECT * from TBL_A A inner join TBL_B B on A.[NO] B.[NO] where A.[NO] IN (" & noStr & ") AND B.[TYPE] = 1;" rs.Open strSQL, cn rs.MoveFirst ActiveSheet.Range("A1").CopyFromRecordset rs If Not rs Is Nothing Then If rs.State = adStateOpen Then rs.Close Set rs = Nothing End If Next If Not cn Is Nothing Then If cn.State = adStateOpen Then cn.Close Set cn = Nothing End If End Sub
0 件のコメント:
コメントを投稿