RecordSet to CSV in VBScript

While I’m in a temporary hell maintaining some VBScript, I thought I’d should share this. RecordSet’s GetString method is inadequate for properly quoting CSV, so I had to write this.

<%

Public Function RecordSet2Csv(rs)
    Dim field
    Dim c
    c = 1
    For Each field In rs.Fields
        If field.Name = "" Then
            RecordSet2Csv = RecordSet2Csv & CsvValue_("(computed" & c & ")") & ","
            c = c + 1
        Else
            RecordSet2Csv = RecordSet2Csv & CsvValue_(field.Name) & ","
        End If
    Next
    RecordSet2Csv = RTrimOne_(RecordSet2Csv)
    While Not rs.EOF
        RecordSet2Csv = RecordSet2Csv & vbLf
        For Each field In rs.Fields
            RecordSet2Csv = RecordSet2Csv & CsvValue_(field.Value) & ","
        Next
        RecordSet2Csv = RTrimOne_(RecordSet2Csv)
        rs.MoveNext
    Wend
End Function

Private Function CsvValue_(val)
    If IsNull(val) Then
        CsvValue_ = ""
    Else
        CsvValue_ = """" & Replace(val, """", """""") & """"
    End If
End Function

Private Function RTrimOne_(str)
    RTrimOne_ = Left(str, Len(str) - 1)
End Function

%>

1 thoughts on “RecordSet to CSV in VBScript

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.