如何同时在两个表中插入数据。 [英] How to insert data in two tables simultaneously.

查看:126
本文介绍了如何同时在两个表中插入数据。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC新手



我有两张桌子

员工和用户



I am new to MVC

I have two tables
Employee and Users

Employee              
---------	      
PK_EmployeeID int      
EmpNo string	       	
EmpName string

...



...

Users
-------
UserName string
UserPassword string



Users表中的UserName字段等于Employee中的EmpNo字段。



我想要在创建新员工的同时将记录EmpNo同时插入UserName。

如何在MVC3中实现这一点?

我是否需要在这两个表之间建立任何Pk / Fk关系。


UserName field in Users table is equal to EmpNo field in Employee.

I want to insert the record EmpNo into UserName simultaneously while creating new employee.
how can this be achieved in MVC3 ?
Do i need to make any Pk/Fk Relationship between these two tables.

推荐答案

这里的示例触发了我上面的评论



1.创建触发器 - 运行这在SQL查询分析器



Here the sample trigger further to my comments above

1. Create the trigger - run this in the SQL query analyser

CREATE TRIGGER tr_insert_user 
   ON  dbo.Employee
   AFTER INSERT
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    insert into users (UserName)
	select  EmpName from inserted

END
GO







2.在查询分析器上运行测试查询(将数据插入员工表)






2. Run a test query on the query analyser (insert data into the employee table)

INSERT INTO [dbo].[Employee]
           (
           [EmpName])
     VALUES
           ('Hello')





3.现在是否自动调用触发器(当你有时执行插入语句)并插入带有新条目的users表



在数据库上运行查询以查看此结果





3.Now the trigger is automatically invoked (when ever you do a insert statement) and the users table is inserted with a new entry

Run the query on the database to check this out

select * from users


这篇关于如何同时在两个表中插入数据。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆