如何将数据从表复制到另一个表

时间:2017-03-06 19:39:27

标签: sql-server database

如何将数据从表复制到另一个

  1. 将所有教师(除非与学生具有相同的ID)插入到同一部门的tot_creds = 0的学生表中

  2. 现在删除所有新添加的"学生"上面(注意:已经存在的tot_creds = 0的学生不应该被删除)

  3. 讲师表:

     ID      Name           dept_name    salary
    10101   Srinivasan     Comp. Sci.   65000.00
    12121   Wu             Finance      90000.00
    15151   Mozart         Music        40000.00
    22222   Einstein       Physics      95000.00
    32343   El Said        History      60000.00
    33456   Gold           Physics      87000.00
    45565   Katz           Comp. Sci.   75000.00
    58583   Califieri      History      62000.00
    76543   Singh          Finance      80000.00
    

    学生:

    ID      Name      dept_name    tot_cred
    00128   Zhang     Comp. Sci.    102
    12345   Shankar   Comp. Sci.    32
    19991   Brandt    History       80 
    23121   Chavez    Finance       110
    44553   Peltier   Physics       56
    45678   Levy      Physics       46
    70557   Snow      Physics       0
    

    我试过这个插入但没有任何事情发生0行受影响,请指导我

    insert into student select ID, name, dept_name, 0 
     from instructor 
      where ID != instructor.ID 
    

4 个答案:

答案 0 :(得分:0)

我想你想要这个:

INSERT INTO student (id, name, dept_name, tot_cred)
   SELECT instructor.ID, instructor.name, instructor.dept_name, 0 
   FROM instructor LEFT JOIN student on instructor.ID = student.ID
   WHERE student.ID IS NULL
     AND instructor.tot_cred <> 0

这将插入与现有学生不匹配的非零总学分的教师。你的#2有点神秘,所以我猜你打算用那个部分。

答案 1 :(得分:0)

我会使用browserify -r ./../app/aws/googleAuth.js:googleAuth -r ./../app/aws/awsServices.js:awsServices -r ./../app/bower_components/bluebird/js/browser/bluebird.min.js:Promise -r ./node_modules/aws4/aws4.js:aws4 -g aliasify -r ./../app /aws/config.js:config > ./../app/bundle.js 子句来过滤掉现有记录。

not exists

然后从教练表中删除它们(如果我正确理解第2部分)。

insert into Student (ID, name, dept_name, tot_cred)
select ID, name, dept_name, 0
from Instructor
where not exists (
select 1
from Student
where ID = Instructor.ID
)

但是,这假设ID在Student表和Instructor表之间是全局唯一的。

答案 2 :(得分:0)

INSERT INTO Students
    (ID, Name, dept_name, salary)
SELECT 
    I.ID, I.Name, I.dept_name, I.salary 
FROM 
    Instructors I
LEFT JOIN  
    Students S ON S.ID = I.ID 
WHERE 
    S.ID IS NULL
    AND S.tot_cred <> 0


DELETE FROM  Instructors WHERE ID IN (SELECT ID FROM STUDENT) 

答案 3 :(得分:0)

您可以使用以下方法将数据从一个表复制到另一个表:

--Insert data from one table to another table (same or different dBs)
INSERT INTO DestinationDB.dbo.DestinationTable(ColumnX, ColumnY, ColumnZ, ColumnW, ColumnT)
--If the ID column of the DestinationTable is automatically created (isIdentity) do not insert value to the ID column.
SELECT ColumnA, ColumnB, ColumnC, 'Test', 1 
FROM SourceDB.dbo.SourceTable
WHERE < Search Conditions >

希望这会有所帮助......