
この記事では
・VBScriptから
・SQL Serverへ
・SQLを実行する方法
を記載します!

今回は
・認証方法に「Windows 認証」
・ADOを使用
・Microsoft OLE DB Driver for SQL Serverを使用
します!
※「Microsoft OLE DB Driver for SQL Server」は「OLE DBドライバー」です。
サンプルプログラムの概要
VBScriptから
・SQL Serverへ
・以下のSQLを実行
するVBSファイルを作成します。
SELECT
id,
productName,
price
FROM m_product


サンプルプログラム作成
Option Explicit
'===============================
'接続文字列
'===============================
'プロバイダ
Const PROVIDER = "MSOLEDBSQL"
'サーバー名(サーバーのPC名\インスタンス名)
Const SERVER_NAME= "localhost\SQLEXPRESS"
'DB名
Const DB_NAME = "sampleDB"
Dim con
Dim conStr
Dim coomand
Dim rs
Dim i
'===============================
'SQL Serverへ接続
'===============================
'接続文字列の組み立て
conStr = "Provider=" & PROVIDER & ";" & _
"Data Source='" & SERVER_NAME & "';" & _
"Initial Catalog='" & DB_NAME & "';" & _
"Integrated Security=SSPI;" & _
"DataTypeCompatibility=80;"
'オープン
Set con = CreateObject("ADODB.Connection")
con.Open conStr
'実行するSQLを組み立て
coomand = coomand & "SELECT "
coomand = coomand & " id, "
coomand = coomand & " productName, "
coomand = coomand & " price "
coomand = coomand & "FROM m_product "
SQLを実行し結果を取得
Set rs = CreateObject("ADODB.Recordset")
rs.Open coomand, con
i=1
Do Until rs.EOF
'各レコードの1~3列目を取得
Msgbox i & "行目は" & _
Trim(rs("id").Value) & "," & _
Trim(rs("productName").Value) & "," & _
Trim(rs("price").Value)
i = i + 1
rs.MoveNext
Loop
'===============================
'後片付け
'===============================
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
msgbox "完了!"
接続文字列の詳細については、以下の記事の「サンプルプログラム作成」をご確認ください。
実行結果
上記で作成したVBSファイルを実行すると、
・VBScriptから
・SQL Serverへ
・SQLを実行できた
ことを確認できます。

