Insert Statement + Combining table data and variab

2019-08-07 06:21发布

I'm trying to write a trigger that deals with the following problem. I'm stuck trying to pull out the required variable from the inserted table, combining it with data from another table, and inserting that as one into required table (I know this is sort of vague/confusing, bear with me...)

This is how I want the database to work:

Three tables in the database:

  1. Table Users:
    A table of user information, including an identifying number
  2. Table PlaneGPSCoordinates:
    A table of live GPS coordinates. This table never changes in size, the values are just updated.
  3. Table MatchingInformation:
    A table that has two columns, User ID number and plane coordinates.

The trigger should do the following:

  1. New row inserted into Table "Users" (i.e., a user signs up)
  2. Trigger automatically copies the data in PlaneGPSCoordinates (excluding a key column), and the new User's ID number, and inserts the two into Table MatchingInformation. There will be 1 user ID number for every 5 rows of Coordinates -> i.e., the trigger will add five rows to MatchingInformation, where userID = the new User's ID and coordinates are all copied from table PlaneGPSCoordinates.

Currently, my incomplete code looks like:

CREATE TRIGGER dbo.Matching
ON dbo.UserInfo
FOR INSERT
AS

DECLARE @userID as INT

BEGIN
SET NOCOUNT ON;

SELECT @userID = inserted.ID FROM inserted

INSERT....

END
GO

I'm very new to SQL, so assume the worst. I don't know how to now create the INSERT statement, where it pulls the GPS coordinates, and combines it with the user ID, to push that to the Matching table...

Any help is much appreciated!

1条回答
劫难
2楼-- · 2019-08-07 06:57

You can't treat a trigger as if it handles one row at a time. If the insert happens using a multi-values clause or a nested select, the trigger will fire once for the entire operation, meaning you will only ever handle one arbitrary @UserID.

Here I assume that your PlaneGPSCoordinates table has exactly 5 rows, and that those are the coordinates that every new user gets.

CREATE TRIGGER dbo.Matching
ON dbo.UserInfo
FOR INSERT
AS
BEGIN
  SET NOCOUNT ON;
  INSERT dbo.MatchingInformation(GPS1, GPS2, UserID)
    SELECT p.GPS1, p.GPS2, i.UserID
      FROM dbo.PlaneGPSCoordinates AS p
      CROSS JOIN inserted AS i;
END
GO

But this begs the question, why copy the same coordinates for every user? Is this something they're going to update often, you just want to put some default values there to start with?

查看更多
登录 后发表回答