检查记录是否存在的VBScript

时间:2009-09-14 01:55:02

标签: sql sql-server vbscript filesystems

我有一个表格和一个文本文件。一旦表中的记录复制到textfile中,记录就会被删除。但该表仍在使用中,并将不时插入新记录(由另一个程序)。我要做什么检查如何确保如果表中没有记录,程序将永远不会复制到文本文件中。

任何解决方案或参考都非常感谢。非常感谢你。我在WSH中测试并使用MSSQL Server 2005。

'call functions
  call CopyFile()
  call tblDelete()
Sub tblDelete() Dim sql1 sql1 = "DELETE from tblOutbox" rs = conn.Execute(sql1) End Sub
Sub CopyFile 'set the sql command cmd.CommandText = "SELECT * FROM tblOutbox" cmd.CommandType = 1 ''# adCmdText Command text is a SQL query Dim rs : Set rs = cmd.Execute 'create obj for the FileSystem Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject") Dim objFile, objFolder
Dim strDir, strFile strDir = "c:\" strFile = "\newFile.txt" 'check that the strDirectory folder is exist If objFSO.FolderExists(strDir) Then Set objFolder = objFSO.GetFolder(strDir) Else Set objFolder = objFSO.CreateFolder(strDirectory) WScript.Echo "Just created " & strDir End If If objFSO.FileExists(strDir & strFile) Then Set objFolder = objFSO.GetFolder(strDir) Else Set objFile = objFSO.CreateTextFile(strDir & strFile) Wscript.Echo "Just created " & strDir & strFile End If Set objFile = Nothing Set objFolder = Nothing 'open files and copy into
Dim objtextStream : Set objtextStream = objFSO.OpenTextFile(strDir & strFile, 8, True) Do Until rs.EOF objtextStream.Write rs("id") & ", "
objtextStream.Write rs("ip") & ", " objtextStream.Write rs("msg") & ", " objtextStream.WriteLine rs("date")
rs.MoveNext Loop objTextStream.WriteLine objTextStream.WriteLine "Report Generate at " & Now objTextStream.WriteLine "--------------------------------------------" objtextStream.Close rs.Close
End Sub

2 个答案:

答案 0 :(得分:0)

您是否可以使用以下格式设置代码,在此格式中,您可以延迟打开输出文件,直到您触发查询并检索至少一个响应为止:

Set up SQL statement 
Execute SQL query 
init bFirstRecord as true 
Loop over results   
  if bFirstRecord
   check folder and file existence, create as necessary
   open output file
   bFirstRecord = false   
  end if   
  write record to output 
End Loop
Close up files, etc

答案 1 :(得分:0)

你可以把

If rs.RecordCount > 0 Then
   exit sub
End If

Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objFile, objFolder 

即。如果没有记录,请不要执行任何语句。