Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi All
Can you please let me know how a VBSCript can connect to a SQL Server, run a pre-defined stored procedure (a simple select that returns a table results), then output the table into a file and save it at a location?
Many thanks!
aiko

Untested, as I don't have SQL Server
Dim cn, rs
Dim fout
Dim i
Dim line
Const Server = "yourServer"
Const DB = "yourDatabase"
Const Uid = "yourUsername"
Const Pwd = "yourPassword"
Const Proc = "yourProcedure"
Const outFile = "out.csv"
'Open output file
With CreateObject("Scripting.FileSystemObject")
Set fout = .OpenTextFile(outFile, 2, True)
End With
'Connect to database
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "SQLNCLI"
.ConnectionString = "Server=" & Server & _
";Database=" & DB & _
";Uid=" & Uid & _
";Pwd=" & Pwd & ";"
.CursorLocation = 3
.Open
End With
'Run procedure
Set rs = CreateObject("ADODB.Recordset")
rs.Open Proc, cn, 0, 1, 4
'Dump results to file
Do Until rs.EOF
line = ""
For i = 0 To rs.Fields.Count - 1
If Not IsNull(rs.Fields(i).Value) Then
line = line & ",""" & rs.Fields(i).Value & """"
Else
line = line & ","
End If
Next 'i
fout.WriteLine Mid(line, 2)
rs.MoveNext
Loop
'Clean up
out "#[EoS]#"
rs.Close
cn.Close
fout.Close
Sub out(s)
On Error Resume Next
WScript.StdOut.WriteLine s
End Sub

![]() |
Speeding up a script i us...
|
Batch that creates batch ...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |