将数据库表中的列导出到文本文件

时间:2014-07-08 05:16:57

标签: sql vbscript

我有下面的代码,它将数据库表的内容复制到文本文件中,但我只想要该表的一个特定列。

Sub OnClick(Byval Item)                 
  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;"
  connectString="Provider=MSDASQL.1;Persist Security Info=False;Data Source=LocalServer;Initial Catalog=FOX_REPORTS"
  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 _
    "DATALOG", _
    dbConnIn, _
    adOpenStatic, _
    adLockReadOnly, _
    adCmdTable

  Set shell=CreateObject("WScript.Shell")
  Set fso=CreateObject("Scripting.FileSystemObject")
  Set ts=fso.OpenTextFile("C:\DATALOG.TXT",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
End Sub

1 个答案:

答案 0 :(得分:1)

替换

rs.Open _
  "DATALOG", _
  dbConnIn, _
  adOpenStatic, _
  adLockReadOnly, _
  adCmdTable

rs.Open _
  "SELECT [colname] FROM DATALOG", _
  dbConnIn, _
  adOpenStatic, _
  adLockReadOnly

其中colname是您要导出的列的名称。