我创建了以下代码,以便插入两个表Users
和Roles
:
- 插入Users表
declare @u int
set @u = 1000
while @u <= 1200
begin
insert into Users(UserID, Username, [Password], Email)
values(@u,
'Username'+CAST(@u as varchar(4)),
'pass'+CAST(@u as varchar(4)),
'Email'+CAST(@u as varchar(4)))
set @u = @u + 1
end
--to insert into the Roles table
declare @a int
set @a = 1
while @a <= 100
begin
insert into Roles (RoleID, [Role], [Description])
values(@a, 'Admin', 'description’ + CAST(@a as varchar(4)))
set @a = @a + 1
end
现在我想对一个名为'User_Roles'的表做同样的事情,它从Users
表中得到两个外键,从Roles
得到另外一个。我写了以下内容:
declare @b int
set @b = 1
while @b <= 300
begin
insert into User_Roles(UserID, RoleID, [Description])
select
UserID, RoleID, 'Description' + CAST(@b as varchar(4))
from Users, Roles
where UserID = CAST((RAND()*200+1000) as int)
and RoleID = CAST((RAND()*99+1)as int)
set @b = @b + 1
end
两个第一个代码将正确执行,但最后一个代码会导致错误,因为它会在主键中插入重复值。如何更改最后一部分并解决此问题?
答案 0 :(得分:0)
修改INSERT语句以包含GROUP BY,以消除UserID和RoleID重复项。
insert into User_Roles(UserID, RoleID,[Description])
select UserID, RoleID,'Description'+CAST(@b as varchar(4))
from Users, Roles
where UserID = CAST((RAND()*200+1000) as int)
and RoleID = CAST((RAND()*99+1)as int)
GROUP BY UserID, RoleID
答案 1 :(得分:0)
每次循环时,都必须确保插入一个尚不存在的值。
未经测试,但这样的事情应该有效:
insert into User_Roles(UserID, RoleID, [Description])
select
u.UserID, r.RoleID, 'Description' + CAST(@b as varchar(4))
from Users u, Roles r
where u.UserID = CAST((RAND()*200+1000) as int)
and r.RoleID = CAST((RAND()*99+1)as int)
and NOT EXISTS(SELECT 1 from User_Roles ur WHERE ur.UserID = u.UserID AND ur.RoleId = r.RoleId)