我有 3 个表形成多对多关系,如下图所示。
如何UsersByCompanies
使用以下规则在公司编号 1 和用户编号 2 之间保存表中的条目:
- 当我们在用户和公司之间创建新条目时,
IsEnabled
属性 inUsersByCompanies
必须设置为 1,并且任何其他行Companies.CompanyCode = 1
的属性Users.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'