Friday, March 9, 2012

Insert same data to two different tables with one submit button....

I would like to insert a set of data to my database to 2 different tables.
what will be the SQL Statement for such ? Is it possible to do so?

for example, a webpage contain 2 textbox which require user to key in data. Once click submit button. the info will saved to 2 tables...you can pass the data to a stored procedure and from there insert the data into as many tables as you need...( all in one trip)

hth|||Hie, thanks for replying me...

I'm not very clear with what u say...
u mean create 1 store procedure or 2 store procedure. Can u show me theSQL statement how to insert ?

for example:

dim mysqlcommand as new SqlCommand("insert into Table1 (name) values (@.name)", mycon)

Let say this is the initial command for one insert statement, how to insert the same thing to another Table ?
U were saying using SP, can u show me the statement...?

Thanx...|||There are a few ways to do it, but you can't do it in one SQL statement.

You would have to create to two insert statements inside a stored procedure.

You asked for an example of a SPROC, this should work:

CodeBehind (not tested):


Dim cmd As New SqlCommand
cmd.Connection = conn 'Or your connection string
cmd.CommandText = "YourSprocName"
cmd.CommandType = CommandType.StoredProcedure

sqlpar = cmd.Parameters.Add("@.Name", SqlDbType.VarChar, 50)
sqlpar.Value = tbName.Text

If conn.State = 0 Then conn.Open()
cmd.ExecuteNonQuery()

cmd.Dispose()
conn.Close()

SPROC (not tested):


CREATE PROCEDURE dbo.YourSprocName
(
@.Name AS varchar(50)
)
AS
INSERT INTO Table1
(Name) VALUES (@.Name)

INSERT INTO Table2
(Name) VALUES (@.Name)

GO


Another alternative would be to build a trigger on the Table1 that would insert into Table2.

A third alternative would be to duplicate the in-line SQL on your page. (this method is recommended the least, I recommend doing as much as you can in SPROCS)

No comments:

Post a Comment