Search code examples
c#asp.netsqldatabasemultiple-databases

ASP.net Connecting to two databases at once?


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.


Solution

  • 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