We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Update from table of a database to another table of another database.

Medium Priority
272 Views
Last Modified: 2012-05-07
Hi,

I have below situation.

I have 2 databases.

1. Inventory.
2. Accounting.

The user just input data using "Invoicing Menu" and press "Save" button.

I want to post the transaction into those database table.

TableSales in database Inventory.
TableJournal in databse Accounting.

I still want to use Transaction (Begin, Commit and Rollback) for both of them, in case something happened to one of them.

How could achieve this?

Thank you.

Comment
Watch Question

AneeshDatabase Consultant
CERTIFIED EXPERT
Top Expert 2009

Commented:
you have to use the 3 part naming conventions ( databaseName.dbo.TableName )



beging tran
 insert into Inventory.dbo.Sales select ....
 insert into Accounting.dbo.TableJournal select ....

Author

Commented:
Hi aneeshattingal,

Some questions:

1. Which connection should I use.
2. Select from what table, since we can not read Inventory Table because it is not commit yet.

Thank you.
here is a good example.
http://msdn.microsoft.com/en-us/library/2k2hy99x(VS.71).aspx
Basically you should use the same transaction object for both sqlcommands. On error you rollback.

Author

Commented:
Hi shahprabal,

Thanks for the link. I have knowledge about this.

1. Which connection should I use.
Basically you should use the same transaction object for both sqlcommands. On error you rollback.

2. Select from what table, since we can not read Inventory Table because it is not commit yet.
How about this point? The problem what I am facing is here.

Thank you.


AneeshDatabase Consultant
CERTIFIED EXPERT
Top Expert 2009

Commented:
>2. Select from what table, since we can not read Inventory Table because it is not commit yet.
You can read from the table within that transaction, it wont make the changes unless you commit them

Author

Commented:
Hi aneeshattingal,

- You can read from the table within that transaction, it wont make the changes unless you commit them
No, I can not read it, since it is locked by SQL cause waiting till Timeout.

Thank you.


AneeshDatabase Consultant
CERTIFIED EXPERT
Top Expert 2009

Commented:
create table test1 ( i int )
create table test2 ( j int)

begin tran
 insert into test1 select 1
 insert into test2 select * from test1
 select * from test1
 select * from test2
go
commit tran
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Author

Commented:
Hi aneeshattingal,

Yes, it works, may be I used different connection. that's why I can not read it?
But it use one database, does it the same for different database?

Thank you.
@ aneesh, the query that you posted will try to get executed as a whole if I am understanding it correctly. So how does the user know where the transaction failed?  

Author

Commented:
Hi shahprabal,

I have no idea how to code it.

Would you please provide simple sample?

Thank you.
You code it just like in the example except for one minor change :
            Dim sqlTran As SqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
instead of
            Dim sqlTran As SqlTransaction = connection.BeginTransaction()

        Using connection As SqlConnection = New SqlConnection(connectString)
            connection.Open()
 
            ' Start a local transaction.
            Dim sqlTran As SqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
 
            ' Enlist the command in the current transaction.
            Dim command As SqlCommand = connection.CreateCommand()
            command.Transaction = sqlTran
 
            Try
                command.CommandText = _
                  "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')"
                command.ExecuteNonQuery()
                command.CommandText = _
                  "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')"
                command.ExecuteNonQuery()
                sqlTran.Commit()
                Console.WriteLine("Both records were written to database.")
            Catch ex As Exception
                Console.WriteLine(ex.Message)
                Console.WriteLine("Neither record was written to database.")
                sqlTran.Rollback()
            End Try
        End Using

Open in new window

Author

Commented:
Hi shahprabal,

I use 2 database and 2 tables.
I read table1 in database1 to insert table2 in database2.

Thank you.
Are you just reading the data from table1? If so you can do a insert into like so :
INSERT INTO Insurance (Name)
    SELECT Employee.Username FROM Employee
    INNER JOIN Project ON Employee.EmployeeID = Project.EmployeeID
    WHERE Project.ProjectName = 'Hardwork';  
http://www.devguru.com/technologies/t-sql/7124.asp
I don't know what you need help with.. the sql to get the insert to work or help with the transaction. If you can't get the transaction to work then look at the isolation level. It doesn't matter if they are in different db or not (since they are on the same server). Post your query if you need more help.

Author

Commented:
Please see below code.

Try
                command.CommandText = _
                  "INSERT INTO Database1.Table1(Name) VALUES('Wrong size')"
                command.ExecuteNonQuery()
                command.CommandText = _
                  "INSERT INTO Database2.Table2(Name) SELECT  Name FROM Database1.Table1"
                command.ExecuteNonQuery()
                sqlTran.Commit()
                Console.WriteLine("Both records were written to database.")
            Catch ex As Exception
                Console.WriteLine(ex.Message)
                Console.WriteLine("Neither record was written to database.")
                sqlTran.Rollback()
            End Try

Could it work?

Thank you.


Ok so you are inserting, then reading the value for another insert... so all you need to do to get this to work is add:
sqlTrans.Isolationlevel = IsolationLevel.ReadCommitted
after you declare the trans or declare it as :
Dim sqlTran As SqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

Author

Commented:
I just need Dim sqlTran As SqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)  to make it work?

Thank you.



 

Author

Commented:
Hi shahprabal,

It is solved now.

Thank you very much for your help.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.