如何使用存储过程将数据插入和更新到两个表中

问题描述:

表1: loginID(PK),名称

表2: loginID(FK),UserRole,代理商



如何使用1个存储过程将数据插入和更新到两个表中?



条件:如果我们第一次创建新的loginID,那么它应该允许我们直接插入数据但是如果loginID已经存在,那么它应该根据loginID将数据更新到两个表中。



请同样建议。

提前致谢。

Table 1: loginID(PK), name
Table 2: loginID(FK), UserRole, agency

How can we insert and update data into both tables using 1 stored procedure?

condition: if first time we are creating new loginID, then it should allow us to insert data directly but if loginID already exists then it should update the data into both table based on loginID.

Please suggest on the same.
Thanks in advance.

这比你想象的容易得多。执行以下操作:



This is much easier than you think. Do something like the following:

IF EXISTS(SELECT * FROM Table1 WHERE loginID = @loginID)
  BEGIN
    -- record exists so do update
    UPDATE table1 SET field1 = @value1
    UPDATE table2 SET field1 = @value1
  END
ELSE 
  BEGIN 
    -- record does not exist so do insert
    INSERT INTO TABLE1(field1, field2)
    VALUES (@field1, @field2)
  END