C#sql将数据从一个表插入另一个表 [英] C# sql insert data from one table to another
问题描述
我的数据库中有两个表。
students_table和student_details表。
我需要从students_table获取所有学生姓名并将其插入student_details表中不存在如何做到这一点?
从students_table中选择姓名,
每个姓名
如果在student_details表中不存在而不是插入它。
所以,我用select查询填充数据表并获取所有值,如何在student_details表中插入它们。
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.
推荐答案
你应该复制ID而不是名。不要将名称用作ID;使用无意义的东西 - 比如整数或GUID。
有几种方法。一种方法是使用带有JOIN的INSERT / SELECT:
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
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);
如果您使用sql server 2008或信件,那么您可以使用
if oracle then
If you use sql server 2008 or letter then you can use
if oracle then
insert into student_details(name)
select name from student_table
minus
select name from student_details
如果sql server那么
if sql server then
insert into student_details(name)
select name from student_table
except
select name from student_details
这篇关于C#sql将数据从一个表插入另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!