Computing.Net > Forums > Programming > VBScript to connect to SQL Server

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

VBScript to connect to SQL Server

Reply to Message Icon

Name: aiko
Date: October 18, 2008 at 01:22:57 Pacific
OS: Windows XP
CPU/Ram: Dell
Comment:

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



Sponsored Link
Ads by Google

Response Number 1
Name: Razor2.3
Date: October 20, 2008 at 19:13:09 Pacific
Reply:

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


0
Reply to Message Icon

Related Posts

See More


Speeding up a script i us... Batch that creates batch ...



Post Locked

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


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: VBScript to connect to SQL Server

import files to SQL server www.computing.net/answers/programming/import-files-to-sql-server/10825.html

how to used perl connect MS SQL Se www.computing.net/answers/programming/how-to-used-perl-connect-ms-sql-se/6259.html

connecting sql server from java www.computing.net/answers/programming/connecting-sql-server-from-java/11451.html