Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
4.33/5 (3 votes)
See more:
I have two tables in my database.
students_table and student_details table.
I need to get all student names from students_table and insert them in student_details table if they already don't exist. how can this be done?
Select Name from students_table,
for each Name if it does not already exist in student_details table than insert it.
So, i populate a data table with select query and get all the values, how do i insert them in student_details table.
Posted

You should be copying IDs rather than names. Do not use names as IDs; use something meaningless -- like an integer or a GUID.

There are several ways. One way to do that is with an INSERT/SELECT with a JOIN:

INSERT INTO Child ( ID )
SELECT A.ID FROM Parent A
LEFT OUTER JOIN Child B
ON A.ID=B.ID
WHERE B.ID IS NULL
 
Share this answer
 
SQL
create table  student_details(roll int identity, name varchar(10));
insert into  student_details(name) values('A'), ('B');

create table  student_table(sl int identity, name varchar(10));
insert into  student_table(name) values('A'), ('B'), ('C'), ('D');

insert into student_details(name)
select name from  student_table where name not in(select name from student_details);
 
Share this answer
 
v4
If you use sql server 2008 or letter then you can use

if oracle then
SQL
insert into student_details(name)
select name from student_table
minus
select name from student_details


if sql server then
SQL
insert into student_details(name)
select name from student_table
except
select name from student_details
 
Share this answer
 
v3
Comments
Raja Sekhar S 24-Oct-13 1:09am    
This one Works for Oracle.... not for Sql Server
S. M. Ahasan Habib 24-Oct-13 2:48am    
thanks
This is how i did it.
C#
foreach (DataRow row in dt.Rows)
            {
                con.Open();
                    string query = "use Sit302GroupProject " +
                        "If Not Exists(select * from Preferences where student_id =" + row["student_id"]+ ") INSERT INTO preferences (student_id) VALUES (" + row["student_id"] + ")";

                    SqlCommand cmd = new SqlCommand(query, con);

                    cmd.ExecuteNonQuery();
                    con.Close();
            }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900