Question: I want to insert data using a while loop in SQL . I have two tables, i already created a while loop but it does
I want to insert data using a while loop in SQL . I have two tables, i already created a while loop but it does not work, i have The INSERT statement conflicted with.... error , here my tables and my while loop, any solution? the problem comes from the foreign key constraint i am adding values in column contact_id table contactInfo that does not exist in addressId column in address table? i dont know how to do this using a while loop
create table Address ( addressID int IDENTITY(1000,1) NOT NULL, Street varchar(50) NOT NULL, City varchar(20) NOT NULL, State char(2) NOT NULL, ZIP char(10) NOT NULL,
primary key (addressID));
create table contactInfo ( contactID int IDENTITY (100,1) NOT NULL, telephone char(10) NOT NULL UNIQUE, Email varchar(50) NOT NULL UNIQUE, address_ID int NOT NULL,
PRIMARY KEY(contactID), FOREIGN KEY (address_ID) references Address(addressID));
DECLARE @J AS INTEGER DECLARE @addressID INTEGER SET @J = 1 WHILE @J <= 50 BEGIN SET @addressID = 100*RAND()+1 WHILE EXISTS (SELECT address_ID FROM contactInfo WHERE address_ID = @addressID) SET @addressID = 100*RAND()+1 INSERT INTO contactInfo(telephone,Email,address_ID) VALUES (cast(cast(9999999999*rand(checksum(newid())) as bigint) as char(10)), 'user' + LTRIM(STR(@j)) + '@mail.com', @addressID) SET @J = @J + 1 END
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
