By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,115 Members | 898 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,115 IT Pros & Developers. It's quick & easy.

INSERT without knowing database column order?

P: n/a
Currently, my code reads from a database without knowing the order of the
columns like this:

string name = (string)datarow["name"];
However, is there a way to write or do an INSERT back to a database without
getting caught up in the order of the columns?

Right now I do something like this, which is delicate and breaks if the
order of the columns changes:

database.ExecuteNonQuery("INSERT INTO dbtable VALUES ('texas', 'austin',
1971)";

Thanks in advance!


Nov 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"AdamM" <no****@nospam.com> wrote in message
news:bJ********************@comcast.com...
However, is there a way to write or do an INSERT back to a database
without getting caught up in the order of the columns?


"INSERT INTO dbtable (state, city, date) VALUES ('texas', 'austin', 1971)";

Obviously, amend the column names accordingly :-)

Otherwise, use a parameterised stored procedure.
Nov 17 '05 #2

P: n/a
AdamM wrote:
Currently, my code reads from a database without knowing the order of the
columns like this:

string name = (string)datarow["name"];
However, is there a way to write or do an INSERT back to a database without
getting caught up in the order of the columns?

Right now I do something like this, which is delicate and breaks if the
order of the columns changes:

database.ExecuteNonQuery("INSERT INTO dbtable VALUES ('texas', 'austin',
1971)";

Thanks in advance!


You can use the "full" syntax:
INSERT INTO <tablename> (<columnlist>) VALUES (<valuelist>)

for instance (guessing a bit)
INSERT INTO dbtable (state, town, year) VALUES ('texas', 'austin', 1971)

the order of values needs to be the same as the columns ("1971" maps to
"year"), but it is independent of the order in the table definition.
You can also skip columns this way, to have the database use the defined
default values.
--
Hans Kesting
Nov 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.