Click here to Skip to main content
15,851,711 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Insert Data in Sql Server using function

using VB.Net
i want to make an insert fucntion or method or class

who work with any table and any column
with out any changes
what should i do for these code
i just add
dim table as string
table = scott

means no change any things in function
just give table name and values to insert....

[edit]Spurious formatting removed, code blocks added - OriginalGriff[/edit]
Updated 30-Apr-13 2:30am

1 solution

In all probability, you can't do that, or not without a lot of work to create a generic routine.
The table name is no problem: just insert it into your SQL INSERT statement:
Dim sqlCommand as String = "INSERT INTO " & tableName & "...
The problem comes with the actual table data itself.
Unless you know exactly what the table holds, there is a very good chance that the insert will fail: because you are trying to be generic about this, you can't list the columns that you are going to insert, so you don't know how many rows worth of data you are trying to insert. Since the SQL INSERT statement is row based, this becomes a real problem.

In addition, if any of your columns are Identity fields, you cannot supply a value for them so you have to explicitly name the fields you do wish to load in the INSERT statement (and it's considered good practice to do so anyway).

To be honest, I wouldn't do it - just use a DL that "knows" about the database structure and save data that way instead.
Share this answer
saimm 2-May-13 2:27am    
thanks but this answer make confuse
OriginalGriff 2-May-13 3:57am    
That's checking to see if a specific column with a name exists in a table: that has nothing to do with your "generic" method which doesn't now what table it is until it is called, much less what columns it should have!
saimm 2-May-13 5:34am    
ok thanks So Much OrignalGriff
its realy helpful
OriginalGriff 2-May-13 5:35am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900