根据表到表更新字段?

时间:2011-03-16 16:49:04

标签: sql-server sql-server-2005 tsql

我处于脑力激增的境地。我想,让我们向极客解释,所以他们可以帮我解决这个问题。

我在Oracle中有一个名为Sharepoint_Users的表。 (见下面的格式和数据)。我从链接服务器访问oracle db。不用担心。只要考虑它是sql表。

SharePoint_Users

ID         Status
1           Active
2           InActive
3           Active
4           InActive

SQL Server中另外两个名为aspnet_user和aspnet_UsersInRoles的表。

aspnet_users
UserID                                       UserName      

A7DFDDAE-4DB8-476D-9C29-677763406F71          1
D9910E14-9206-4460-88CA-4C39DE620192          2
F188B1DF-03A6-4332-BA89-3B3C6682E9BA          3
728E77E7-693A-4015-92CA-02F0A403C29A          4

asnet_usersInRoles

UserID                                      RoleID

A7DFDDAE-4DB8-476D-9C29-677763406F71        1E36A840-2EBB-44EC-8861-0E3D262AC676 ----> InActive
D9910E14-9206-4460-88CA-4C39DE620192        0B54F223-E0D4-4CFC-84C3-7C98C1BFC6DA --->Active

现在是挑战。

* When users status changes in SharePoint_Users table from 'Active' to 'InActive'
 OR 'InActive' to 'Active'. We need to update same users RoleID in 
 asnet_usersInRoles table.


* And also I need insert new records those not exists in asnet_usersInRoles 
  table but exists in aspnet_users table.
  If user not found in aspnet_users should not insert them into 
  asnet_usersInRoles.(always users will be the same SharePoint_Users 
  and aspnet_users)

请帮我写一个sp来完成它。我将每1小时为此sp运行一次更新。

2 个答案:

答案 0 :(得分:0)

为了能够在SharePoint_Users更改时更新,我猜你需要一个触发器,但你也写道,你将每1小时运行一次SP所以......

无论如何,这里是第二部分的插入语句和第一部分的更新语句。由于您不知道哪些行已更改,因此更新会更新所有行。

insert into asnet_usersInRoles(UserID, RoleID)
select
  UserID,
  case s.[Status] when 'Active'
    then '0B54F223-E0D4-4CFC-84C3-7C98C1BFC6DA'
    else '1E36A840-2EBB-44EC-8861-0E3D262AC676'
  end
from aspnet_users as au
  inner join (select ID, min([Status]) as [Status]
              from SharePoint_Users
              group by ID) as s
    on au.UserName = s.ID
where not exists (select *
                  from asnet_usersInRoles as uir
                  where au.UserID = uir.UserID)

update asnet_usersInRoles
set RoleID = case s.[Status] when 'Active'
               then '0B54F223-E0D4-4CFC-84C3-7C98C1BFC6DA'
               else '1E36A840-2EBB-44EC-8861-0E3D262AC676'
             end
from asnet_usersInRoles as uir
  inner join aspnet_users as u
    on uir.UserID = u.UserID
  inner join (select ID, min([Status]) as [Status]
              from SharePoint_Users
              group by ID) as s
    on u.UserName = s.ID  

答案 1 :(得分:0)

当您希望在更新另一个表时修改表中的数据时,请使用触发器:

CREATE TRIGGER SharePoint_Users_Trg_Upd ON SharePoint_Users
AFTER UPDATE
AS
/* update statements here */
GO

这样你就不需要sp每小时听一次。