tags:

views:

184

answers:

6

I've been asked to implement some code that will update a row in a ms sql database and then use a stored proc to insert the update in a history table. We can't add a stored proc to do this since we don't control the database. I know in sprocs you can do the update and then call execute on another stored proc. Can I set it up to do this in code using one sqlcommand?

A: 

You can also create sql triggers.

dpollock
If he can't create a Stored Procedure, he almost certainly can't create a Trigger
foxxtrot
A: 

Depending on your library, you can usually just put both queries in one Command String, separated by a semi-colon.

foxxtrot
Thanks, it's ms sql using vb.net 2005. I will try the semi-colon.
osp70
A: 

Insufficient information -- what SQL server? Why have a history table?

Triggers will do this sort of thing. MySQL's binlog might be more useful for you.

You say you don't control the database. Do you control the code that accesses it? Add logging there and keep it out of the SQL server entirely.

JBB
The history table is used by the application to show updates to the items. Not just a transactional log for recovery.
osp70
+1  A: 

Either run them both in the same statement (separate the separate commands by a semi-colon) or a use a transaction so you can rollback the first statement if the 2nd fails.

Joel Coehoorn
Gave you the accept since this prompted me down the right path. Thanks.
osp70
+1  A: 

You don't really need a stored proc for this. The question really boils down to whether or not you have control over all the inserts. If in fact you have access to all the inserts, you can simply wrap an insert into datatable, and a insert into historytable in a single transasction. This will ensure that both are completed for 'success' to occur. However, when accessing to tables in sequence within a transaction you need to make sure you don't lock historytable then datatable, or else you could have a deadlock situation.

However, if you do not have control over the inserts, you can add a trigger to certain db systems that will give you access to the data that are modified, inserted or deleted. It may or may not give you all the data you need, like who did the insert, update or delete, but it will tell you what changed.

Nathan Feger
A: 

Thanks all for your reply, below is a synopsis of what I ended up doing. Now to test to see if the trans actually roll back in event of a fail.

sSQL = "BEGIN TRANSACTION;" & _
           " Update table set col1 = @col1, col2 = @col2" & _
           " where col3 = @col3 and " & _
           " EXECUTE addcontacthistoryentry @parm1, @parm2, @parm3, @parm4, @parm5, @parm6; " & _
           "COMMIT TRANSACTION;"
osp70
Yep, removed the stored proc in my test environment and when the sql threw an error the update must have been rolled back because the info was the same as the start. Thanks everyone!
osp70