在更新任何旧数据时插入多对多表

时间:2012-11-26 21:23:34

标签: sql sql-server many-to-many

我有3个表格形成多对多关系,如下图所示。

enter image description here

如何使用以下规则在公司编号1和用户编号2之间的UsersByCompanies表中保存条目:

  • 当我们在用户和公司之间创建新条目时,IsEnabled中的UsersByCompanies属性必须设置为1,其他行Companies.CompanyCode = 1Users.IDNumber = 2必须将IsEnabled属性设置为0。
  • 新行中的DateCreated属性必须包含当前日期。

到目前为止,我已经提出了这个问题,但它有错误:

 IF (NOT EXISTS((select IDNumber from dbo.tb_Users where ((IDNumber)) = 1234)))
    --the user was not registered 
    insert into dbo.tbUsers(IDNumber, Name, LastName, department)
    values (1234, 'John','Smith','A')
    go

    insert into dbo.tb_UsersByCompanies (IDNumber,  CompanyCode, DateCreated, IsEnabled)  
    values (1234, 2, getdate(), 1) 
    go

    print 'New Client'

 ELSE 
    update dbo.tbUsers 
    set IDNumber = 1234, Name = 'John', LastName= 'Smith'
    where ((IDNumber)) = 1234
    go

IF (EXISTS((select IDNumber, CompanyCode from dbo.tb_UsersByCompanies 
            where (IDNumber)= 1234 and CompanyCode = 2 and IsEnabled = 1 )))

    --The user is already registered in the company
    print 'The user is already registered and active in the company'

ELSE
    IF(EXISTS((select IDNumber, CompanyCode from dbo.tb_UsersByCompanies 
               where (IDNumber)= 1234 and  IsEnabled = 1 )))
     --the user is active in another company
     update dbo.tb_UsersByCompanies 
     set IsEnabled = 0 
     where ((IDNumber)) = 1234 and IsEnabled = 1 

     insert into dbo.tb_UsersByCompanies (IDNumber,  CompanyCode, DateCreated, IsEnabled)  
     values (1234, 2, getdate(), 1) 

     print 'The Client is active in another company'

  ELSE 
     --if it enters here the user was already registered but not linked to a company
     insert into dbo.tb_UsersByCompanies (IDNumber,  CompanyCode, DateCreated, IsEnabled)  
     values (1234, 2, getdate(), 1)

     print 'the user was already registered but not linked to a company'

1 个答案:

答案 0 :(得分:0)

IF NOT EXISTS(select * from dbo.tb_Users where IDNumber = 1234)
    --the user was not registered 
    insert into dbo.tbUsers(IDNumber, Name, LastName, department)
    values (1234, 'John','Smith','A')
 ELSE 
    update dbo.tbUsers 
    set IDNumber = 1234, Name = 'John', LastName= 'Smith'
    where ((IDNumber)) = 1234

  -- now user is valid and existing
  -- update all entries for user which are not company 2
update dbo.tb_UsersByCompanies set IsEnabled = 0 
where  IDNumber= 1234 and CompanyCode <> 2

-- insert if not existsing 
if not Exists (Select * from dbo.tb_UsersByCompanies where  IDNumber= 1234 and CompanyCode =2)
    insert into dbo.tb_UsersByCompanies (IDNumber,  CompanyCode, DateCreated, IsEnabled)
    Values
    (1234,2,GETDATE(),2)