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
IF NOT EXISTS (SELECT ID2 FROM [tbl2] WHERE ID1 = @ID2)
(SELECT 2ID FROM [tbl2] WHERE ID1 = @ID1) SET @identHolder = @@Identity
INSERT INTO [t2] ([fName], [lName], [shift], [userName], [emailAdd])
VALUES ( @fName, @lName, @shift, @userName, @emailAdd) SET @identHolder = @@Identity
SET @ID2 = (@@Identity)
INSERT INTO [tbl1]([ID1], [ID2], [event], [removed])
VALUES (@ID1, @ID2, @event, @removed)
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.
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.