SQL Trigger for Insert

ginolaitano
ginolaitano used Ask the Experts™
on
Experts,

I have two tables. Table USERS with PK userid and the other is USERPROFILE with PK profileid Among other fields.
I need one trigger for when inserting new users to USERS table the trigger creates one record on USERPROFILE table with the value of userdId from users....

Yes, simple but ! Sorry to bother. I need help cake doe!!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Research & Development Manager
Commented:
Sample code:

CREATE TABLE Users(
      Id SMALLINT IDENTITY(1, 1) NOT NULL,
      Name VARCHAR(50) NOT NULL,
      DOB DATETIME NOT NULL,
      CONSTRAINT pkUsers PRIMARY KEY (Id)
)
GO
CREATE TABLE Profiles(
      Id_User SMALLINT NOT NULL,
      Name VARCHAR(50) NOT NULL,
      DOB DATETIME NOT NULL,
      EMail VARCHAR(255),
      LastUpdate DATETIME NOT NULL DEFAULT GETDATE(),
      CONSTRAINT pkProfiles PRIMARY KEY (Id_User),
      CONSTRAINT fkProfiles_Users FOREIGN KEY (Id_User) REFERENCES Users (Id)
)
GO
CREATE TRIGGER tgUsers_Insert
ON Users
FOR INSERT
AS
BEGIN
      INSERT INTO Profiles (Id_User, Name, DOB)
      SELECT Id, Name, DOB
      FROM INSERTED
END
GO
INSERT INTO Users (Name, DOB)
VALUES ('Test User', '1982-01-01')
GO
SELECT * FROM Users
SELECT * FROM Profiles

Author

Commented:
Thank You very much. Works like a charm!
PS: Tks for being so fast!

Author

Commented:
Tks
jorge_torizResearch & Development Manager

Commented:
I thing ginolatinao fails to select the way he accept the solution, its so clear that the solution I provided is correct and he accepted it.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial