Is connecting to two SQL databases at the same time possible ? I mean from one database I am reading records and comparing them with some data like email address and based on the decision that whether that email address exists in the database or not I am storing a new record in another database.
Is this kind of double operation possible ?
I am connecting with databases using SqlConnection and SqlCommand statements of C#.net
Thank you.
Yes this is possible.
You can either return a value to your asp.net application, and then connect to another database like:
cmdEmailExists SqlCommand = new SqlCommand("SQL HERE...", Conn1);
if (((int)cmdEmailExists.ExecuteScalar())>0){
cmdInsert SqlCommand = new SqlCommand("SQL INSERT HERE...", Conn2)
cmdInsert.ExecuteNonQuery();
}
Where Conn1
and Conn2
are 2 different SqlConnection
's connecting to 2 different databases.
Or this can be done at SQL end like:
IF EXISTS(SELECT Email FROM [Database1].dbo.tbl)
BEGIN
INSERT INTO [Database2].dbo.tbl ..........
END
may be this helps you or post ur code
SqlConnection con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con2"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from table1", con1);
SqlDataReader dr;
con1.Open();
dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
while (dr.Read())
{
// ....
}dr.Close()
//your condition then fire insert commnd with connection con2
SqlCommand insertcmd = new SqlCommand("insert into table2", con2);
SqlDataAdapter dap = new SqlDataAdapter(insertcmd);
// ...
This is nice solution but not the correct answer! There is no need of using 2 connection string in order to use 2 different databases on the same server (as long as the user have the right permission). We specify the Initial Catalog during the connection, to define where we want to run the query, but if the user have enough permissions to execute the query on other databases, he can do that using the two dots Db..table notation!
This code will work using one connection string!
SqlConnection con = new SqlConnection(@"Use-connection-string-here");
SqlCommand cmd = new SqlCommand(
"select * from Table1 t1 left join Database2..Table2 t2 on t1.id = t2.id", con
);
来源:https://stackoverflow.com/questions/9600296/asp-net-connecting-to-two-databases-at-once