2

In a C# 2.0 I have a list of fields and a list of values (stored as strings), a table name, and an ODBC Connection.

I need to get the data types of the fields that are on that table, so I know how to generate my sql.

What's the best way to get that information from what I've got?

My only idea is to do a SELECT TOP 0 * FROM @TableName in a data adapter, get back a dataset, and iterate through the list of field names against the datacolumn's in the datatable.

Is there any better way to go about this?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
C. Ross
  • 31,137
  • 42
  • 147
  • 238
  • Unless you need to do this on the fly for some wierd reason, why don't you ask the folks that gave you the rest of the info... or look at it in management studio to find out that info? – John Kraft Jan 30 '09 at 17:36
  • I know what the values are, but I want to make a program generic enough that I can add another request table without changing the code. – C. Ross Jan 30 '09 at 19:57

2 Answers2

4

Try this

select * from sys.columns where object_id = object_id('MyTable')

Hope this helps.

Nick Berardi
  • 54,393
  • 15
  • 113
  • 135
2

You're best option is to query your datbases system tables like Nick Beradi mentioned. If that's not an option for whatever reason, you can do something like this:

using (SqlConnection conn = new SqlConnection(myConnectionString))
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * from MyTable", conn))
                {
                    DataTable table = new DataTable();
                    adapter.FillSchema(table, SchemaType.Mapped);
                    //at this point, table will have no rows, but will have all the columns of which you can get their datatypes
                }
            }
BFree
  • 102,548
  • 21
  • 159
  • 201