tags:

views:

36

answers:

2

I have 2 tables called login and Roles.

In the login table, I have these fields:

CREATE TABLE [dbo].[login]
   ([Id] [int] IDENTITY(1,1) NOT NULL,
[Uname] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Pwd] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

  CONSTRAINT [PK_login_1] PRIMARY KEY CLUSTERED([Uname] ASC)

In the roles table I have these fields:

 CREATE TABLE [dbo].[Roles]
   ([Uname] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Valid] [int] NOT NULL
 ) 

Now what I need is if I fill the uname as some xyz I would like to fill the same uname in the role table automatically in the corresponding field that i makes as foreign key...

+3  A: 

A solution is to put a trigger on inserts to the original table.

This microsoft article on triggers will tell you how they work.

Tobiasopdenbrouw
your answer is technically correct, but conflicts with my religious views on creating a relational database.
Nick Kavadias
@Nick Kavadias: you shouldn't have any religious views when it comes to databases... just opinions based on facts. How would you solve this issue then??
marc_s
@marc_s in my perfect world I wouldn't de-normalize data that way unless there was a very good reason. Like i said, using a trigger is the technical way to do this, but why do it in the first place?
Nick Kavadias
@Nick Kavadias: I don't see this as denormalization - it would appear the link between Roles and Users is done via the `UName` property. Whether that's a good idea (it being a large string) is another story - but if you want to link the two tables on this column, you do need this in both places, no??
marc_s
+3  A: 

You could do this using a Trigger. You may or may not want to execute this code on an Insert and / or Update Further details on triggers can be found here

CREATE TRIGGER trgInsertUserIntoRoles ON Login

FOR Insert

AS    

INSERT INTO Roles (UName, Valid)
SELECT Uname, 1    
FROM Inserted

Although I think it would be better if you just added the code to insert the username into the Roles table within the Stored Procedure to create the user.

Also, you are aware that you are creating all this on the master database?

Barry
+1 for including code.
Tobiasopdenbrouw