views:

322

answers:

2
+1  Q: 

Parsing SQL text

Does anyone know how to parse SQL Text with VB.NET?

Ex: I got a sql file "CREATE TABLE..." i want to get an array of columns and an array of data types.

+4  A: 

It may be the easiest approach to feed that statement to an SQL Server and actually create that table in a temp database.

After that, finding out about the table structure would be easy.

All you'd have to parse out of the statement string would be the name of the table. Even better, you could simply replace it and have a known table name from the start.

Additionally, you would get the info if the statement is even valid SQL.

Tomalak
All I have to do is parse out the statement string, I already know that, I mean "How" can I do it, examples or anything?
No, you misread me. All you'd have do find out and replace is the *table name*, which is an easy exercise with a small substring/indexOf routine (or even a regex, if you know them).
Tomalak
@Tomalak: +1 for patience in response to that comment! ;-)
Cerebrus
Are you on SQL Server? If so...if this is in production and you do not have a temp database, you can create a ## temp table and then do what @Tomalak suggested
Raj More
+3  A: 

Expanding on @Tomalak's post: once you have the table built you can use a DataReader to select just 1 line if you only need the schema or your actual data, then do something like this:

Dim myReader As DataReader
Dim myTable As DataTable

Dim myColumns As New Collection

myReader =  //' get your data

If myReader.HasRows Then
    myTable.Load(myReader)
    For Each col As DataColumn In myTable.Columns
        myColumns.Add(col.DataType.ToString, col.ColumnName)
    Next
End If

The collection myColumns will now have a Key of the column's name and the Value is the columns datatype. You can modify this to make 2 separate collections if you need.

Parsing a string on the other hand will involve significantly more debugging and offer lots of room for error.

Rob Allen
That solve my problem ThanksTheres anyway to retreive the column data type (and its max value)? Thanks
Nvm, i actually got it thanks!
@Rob Allen: Hm... I guess I'll have to vote that up. :-)
Tomalak