Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One option that I would prefer in this case would be to create a stored procedure that takes the necessary input parameters, and then does your two inputs into the two tables in a transaction. That way you control what's going on:</p> <p>(this assumes SQL Server 2005, and the ID fields are INT IDENTITY - correct??)</p> <pre><code> CREATE PROCEDURE dbo.InsertQuestion @Datecreated SMALLDATETIME, @Category_ID INT, @Question NVARCHAR(MAX), @Timelimit SMALLDATETIME, @helper NVARCHAR(MAX) AS BEGIN -- start transaction and a TRY..CATCH block BEGIN TRANSACTION BEGIN TRY -- insert values into "Questions" table INSERT INTO dbo.Questions(DateCreated, Category_ID, Question, TimeLimit, Helper) VALUES (@DateCreated, @Category_ID, @Question, @TimeLimit, @Helper) -- retrieve the ID of the newly inserted row DECLARE @QuestionID INT SET @QuestionID = SCOPE_IDENTITY() -- determine the user ID from SQL Server DECLARE @UserID INT SET @UserID = SUSER_ID() -- insert values into "User_Questions" table INSERT INTO dbo.UserQuestions(QuestionID, UserID, DateCreated, Helper) VALUES (@QuestionID, @UserID, @DateCreated, @Helper) -- commit transaction, if everything went well COMMIT TRANSACTION END TRY BEGIN CATCH -- handle your error, e.g. by logging to a table or something..... ROLLBACK TRANSACTION END CATCH END </code></pre> <p>Triggers are notoriously hard to get right, they don't scale very well - I would try to avoid triggers if ever possible (not always possible, but often, it is) – </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload