VB.NET - INSERT VALUE IN TWO TABLES BY SINGLE SQL QUERY

Asked By anjali sri on 11-Apr-12 03:29 AM
HOW CAN I INSERT VALUE IN TWO TABLES BY SINGLE SQL QUERY BECAUSE IF I'M USING TWO SQL QUERY IT GIVES PROBLEM ME ON BINDING DATA AND CONNECTION
LIKE I HAVE 2 TABLE TABLE 1, TABLE 2
IN TABLE I'M ONLY SAVE ID AND NAME AND IN OTHER TABLE I'M SAVING ID,TIME1,TIME2
Jitendra Faye replied to anjali sri on 11-Apr-12 03:31 AM
For this you need to use trigger.

in single query it is not possible. here you can use After trigger

anjali sri replied to Jitendra Faye on 11-Apr-12 03:35 AM
sory i don't use any trigger or procedure
anjali sri replied to Jitendra Faye on 11-Apr-12 03:35 AM
sory i don't use any trigger or procedure
Somesh Yadav replied to anjali sri on 11-Apr-12 03:41 AM

That sort of unparameterized inline sql will make you a sitting duck for SQL injection attacks. Consider using something like this: 

cmd.CommandText = "Insert into tb1 (col1, col2, col3) values (@col1, @col2, @col3); Insert into tb2 (col1, col2, col3) values (@col11, @col12, @col13);";

cmd
.Parameters.AddWithValue("col1",
"val1"
);


cmd
.Parameters.AddWithValue("col2",
"val2"
);
cmd
.Parameters.AddWithValue("col3",
"val3"
);


cmd
.Parameters.AddWithValue("col11",
"val4"
); cmd.Parameters.AddWithValue("col12",
"val5"
);
cmd
.Parameters.AddWithValue("col13",
"val6"
);
anjali sri replied to Somesh Yadav on 11-Apr-12 03:46 AM
i'm using vb.net
Somesh Yadav replied to anjali sri on 11-Apr-12 03:55 AM

You can actually do it in a single command and even wrap it in a transaction like this:

str1 = "begin tran; "
str1
&= "INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' ); "
str1
&= "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & "); "
str1
&= "commit tran; "

cmd
= New SqlCommand
cmd
.Connection = con
cmd
.CommandType = CommandType.Text
cmd
.CommandText = str1
cmd
.ExecuteNonQuery()

Next you need to use try/catch on a SqlServerException to see what is going wrong. Something like:

try
   
' all your sql code
catch (sqlex as SqlException)
    MessageBox.Show(sqlex.Message)
Also read up on SQL injection
kalpana aparnathi replied to anjali sri on 11-Apr-12 05:40 AM
hi,

Use view concept for getting  desired result instead of use of trigger.

Regards,
anjali sri replied to Somesh Yadav on 11-Apr-12 05:57 AM
thanks it work when i'm convert in to vb.net code
Somesh Yadav replied to anjali sri on 11-Apr-12 07:41 AM
Welcome!