How to copy from a database to a text file using VBScript?

I have an example in C# code, but it is using streamWriter. It must be involving with FileSystemObject rite. If yes, what are methods should I use? I want to code using VBScript WSH, and my database is MS SQL Server 2005.

Any solution, references, or guide are helpful.

  • How do I execute a .SQL file from Excel VBA code?
  • Is there any difference between DECIMAL and NUMERIC in SQL Server?
  • sp_send_dbmail is sending a blank email when the queried table is empty
  • Using SQL Server as a DB queue with multiple clients
  • How to sort sql query having an union statement without specific section
  • SQL Comma separated values with COALESCE
  • using (StreamWriter tw = File.AppendText("c:\\INMS.txt"))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            tw.WriteLine("id, ip address, message, datetime");
            while (reader.Read())
            {
                tw.Write(reader["id"].ToString());
                tw.Write(", " + reader["ip"].ToString());
                tw.Write(", " + reader["msg"].ToString());
                tw.WriteLine(", " + reader["date"].ToString());
            }
            tw.WriteLine("Report Generate at : " + DateTime.Now);
            tw.WriteLine("---------------------------------");
            tw.Close();
            reader.Close();
        }
    }
    

  • TSQL - Count specific values within Multistatement table UDF and pass them to additional column
  • .Net / SQL Server race condition
  • How do I create and query linked database servers in SQL Server?
  • DataReader : Invalid attempt to read when no data is present
  • how to get 30 days from Todays
  • System process is locking my database file MDF
  • One Solution collect form web for “How to copy from a database to a text file using VBScript?”

    In VBScript you need ADODB objects and the FileSystemObject from the Scripting library. Something akin to:-

    Dim conn: Set conn = CreateObject("ADODB.Connection")
    conn.Open "an ole DB mysql connection string", usernameIfneeded, passwordIfNeeded
    
    Dim cmd : Set cmd = CreateObject("ADODB.Command")
    Set cmd.ActiveConnection = conn
    cmd.CommandText = "your SQL code here"
    cmd.CommantType = 1 ''# adCmdText Command text is a SQL query
    
    Dim rs : Set rs = cmd.Execute
    
    Dim fs : Set fs = CreateObject("Scripting.FileSystemObject")
    Dim textStream : Set textStream = fs.OpenTextFile("c:\inms.txt", 8, True)
    textStream.WriteLine "id, ip address, message, datetime"
    Do Until rs.EOF
    
       textStream.Write rs("id") & "," 
       textStream.Write rs("ip") & "," 
       textStream.Write rs("msg") & "," 
       textStream.WriteLine rs("date")   
    
      rs.MoveNext
    Loop
    
    textStream.Close
    rs.Close
    conn.Close
    
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.