Friday, March 23, 2012

Mulit table insert

Can some one point me in the right direction on this. I am trying to insert data into two different table. The problem is, even though table 2 had a "not null" on it's primary, the insert command still allow it to be null.

Here is what I am trying to do. When I click the submit button on my web app, it should send this information in for to table 2. The procedure should then pull the id2 and and enter it into the table as FK to table 1.

Like I said before, the id2 doesn't seem to pass any data because the procedure is passing a null, even thout a set the pk value to not null.


DECLARE @.identHolder int
DECLARE @.ID2 int

BEGIN TRANSACTION
IF NOT EXISTS (SELECT ID2 FROM [tbl2] WHERE ID1 = @.ID2)
BEGIN
(SELECT 2ID FROM [tbl2] WHERE ID1 = @.ID1) SET @.identHolder = @.@.Identity

END
ELSE
BEGIN
INSERT INTO [t2] ([fName], [lName], [shift], [userName], [emailAdd])
VALUES ( @.fName, @.lName, @.shift, @.userName, @.emailAdd) SET @.identHolder = @.@.Identity

END
COMMIT

SET @.ID2 = (@.@.Identity)
INSERT INTO [tbl1]([ID1], [ID2], [event], [removed])
VALUES (@.ID1, @.ID2, @.event, @.removed)I suggest you go back to old school debugging.
Stick a handful of

PRINT @.ID2
--Actually, you'll probably need:
PRINT Convert(varchar, ID2)

And watch the value.
Should the value perhaps be before the COMMIT?|||I figured it out. The "IF Not Exist" needed to be "If exist". I was telling the DB to check for a record but instead of creating the record if not exist, I was selecting it. Once I change that it work. I think I had to fix a datatype too.

Thank you.|||You should also put some error handling after the INSERT to rollback (or whatever) in case of an error (constraint, FK, unique index etc). Use the @.@.ERROR function in SQL Server 2000 and TRY...CATCH in SQL Server 2005.

Many people seems to forget about TSQL error handling.
What should happen if a statement fails? If xact_abort is on the transaction is rolled back and the execution of the batch stops, but if xact_abort is off the transaction remains open and then the batch continues to execute. This can and will lead to lots of problems.|||Do you know of a good site I can go to where I can learn how to write it? I just starting to learn TSQL and not to sure how I would go about creating a proper @.@.ERROR message. Does the @.@.ERROR have to return a value to the application or does it stay with in the db? Thank for the heads up.|||Are you using 2000 or 2005?

@.@.ERROR is the only way in 2000, but as I said, in 2005 you should rather use TRY...CATCH.|||and you probably should use scope_identit() instead|||Linky! (http://codebetter.com/blogs/john.papa/archive/2006/04/07/142503.aspx)
I did not know that :)|||Are you using 2000 or 2005?

@.@.ERROR is the only way in 2000, but as I said, in 2005 you should rather use TRY...CATCH.

I am using 2000

No comments:

Post a Comment