Hi, I have created the following code so as to insert into two tables Users
and Roles
:
-- to insert into the Users table
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
Now I want to do the same for a table named ‘User_Roles’, which get has two foreign key one from Users
table and other from Roles
. I have written the following:
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
The two first code will be executed correctly, but the last one cause an error because it will insert duplicate values in the primary key. How can I change the last part and solve this problem?