我有3个表格形成多对多关系,如下图所示。
如何使用以下规则在公司编号1和用户编号2之间的UsersByCompanies
表中保存条目:
IsEnabled
中的UsersByCompanies
属性必须设置为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'
答案 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)