I try to make a VB script to dump an SQL server table to a CSV file
Option Explicit
Dim rs,fieldVals,dbConnIn
Dim connectString,shell,tmp,fso,ts,line
Const adOpenDynamic=2
Const adLockPessimistic=2
Const adCmdTable=2
Const adOpenForwardOnly=0
Const adOpenStatic=3
Const adLockReadOnly=1
connectString="Provider=SQLOLEDB;Server=192.168.168.4;Database=MYDB;Uid=sa;Pwd=myPassword;"
Set dBConnIn = CreateObject("ADODB.Connection")
dBConnIn.CommandTimeout = 300
dBConnIn.Open connectString
' This is just a simple way of getting a record set from and SQL Query
Set rs=CreateObject("ADODB.RecordSet")
rs.Open _
"TITULARES", _
dbConnIn, _
adOpenStatic, _
adLockReadOnly, _
adCmdTable
Set shell=CreateObject("WScript.Shell")
Set fso=CreateObject("Scripting.FileSystemObject")
Set ts=fso.OpenTextFile("E:\TITULARES.csv",2,TRUE)
line=""
For Each tmp In rs.Fields
line=line & tmp.Name & ","
Next
ts.WriteLine Left(line,Len(line)-1)
While Not rs.EOF
line=""
For Each tmp In rs.Fields
line=line & """" & Replace(tmp.Value,"""","""""") & ""","
Next
ts.WriteLine Left(line,Len(line)-1)
rs.MoveNext
Wend
rs.Close
ts.close
All well, but because some of my SQL table fields are NULL or empty I'm getting this error:
d.vbs(39, 2) Microsoft VBScript runtime error: Invalid procedure call or argument: 'Left'
Any ideas on how to solve this?
Thanks!
BTW..., made it work like this:
Set dBConnIn = CreateObject("ADODB.Connection")
dBConnIn.CommandTimeout = 300
dBConnIn.Open connectString
' This is just a simple way of getting a record set from and SQL Query
Set rs=CreateObject("ADODB.RecordSet")
rs.Open _
"TITULARES", _
dbConnIn, _
adOpenStatic, _
adLockReadOnly, _
adCmdTable
Set shell=CreateObject("WScript.Shell")
Set fso=CreateObject("Scripting.FileSystemObject")
Set ts=fso.OpenTextFile("E:\TITULARES.csv",2,TRUE)
line=""
For Each tmp In rs.Fields
line=line & tmp.Name & ","
Next
ts.WriteLine Left(line,Len(line)-1)
While Not rs.EOF
line=""
For Each tmp In rs.Fields
If IsNull(tmp.Value) Then
line=line & """" & Replace(tmp.Value,"""","""""") & ""","
Else
line=line & """" & tmp.Value & ""","
End If
Next
ts.WriteLine Left(line,Len(line)-1)
rs.MoveNext
Wend
rs.Close
ts.close
Thanks all!