jonlabr
jonlabr

Reputation: 437

VB.NET How to get result in text from SQL Query

With this table :

CREATE TABLE #TEMP(
ID INT,
NAME VARCHAR(30)
)
INSERT INTO #TEMP VALUES(1,'a')
INSERT INTO #TEMP VALUES(2,'b')
INSERT INTO #TEMP VALUES(3,'c')
INSERT INTO #TEMP VALUES(4,'d')
INSERT INTO #TEMP VALUES(5,'e')

And this Query :

print '-----------------------'
select * from #TEMP
print '******************************************'

I need to get the result in text like :

-----------------------
ID          NAME
----------- ------------------------------
1           a
2           b
3           c
4           d
5           e

******************************************

I can get it with SQL Server Management Studio when I select "result in text" or "result in file". How can i get this result by VB.Net?

The las query is only an example. this is my real need :

enter image description here ......

I'm on MS Server 2000. Thank you for your help!

Upvotes: 3

Views: 2810

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460038

You can use ADO.NET and a StreamWriter:

Using stream = New StreamWriter(path)
    stream.WriteLine("----------------")
    stream.WriteLine("ID          NAME")
    stream.WriteLine("----------------")
    Using con = New SqlConnection(YourConnectionString)
        Using cmd = New SqlCommand("select * from #TEMP", con)
            Using reader = cmd.ExecuteReader()
                While reader.Read()
                    stream.WriteLine(String.Format("{0} {1}", reader.GetString(0), reader.GetString(1)))
                End While
            End Using
        End Using
    End Using
    stream.WriteLine("******************************************")
End Using

How to: Write Text to a File

Note that the Using statements ensure that the objects are even disposed in case of an exception.

Upvotes: 4

Related Questions