无法将数据从一个表复制到另一个表,其中id = 1

时间:2013-05-30 06:05:57

标签: sql tsql

嘿伙计们,我在这里相当新手,我想做的是我想要的 将数据(技能)列从一个临时表复制到另一个表,其中id = 1;

现在名为skillmapping的表1具有candidateId和skillName列

Table2只有skillName列

我正在尝试将表2中的数据插入到表1中,其中canidateId = 1

请帮我解决这个问题。我尝试复制数据,但似乎是candidateId的错误.. 感谢。

我尝试了这个,但说错误的语法

 insert into candidateComputerSkillMapping(skillname) values(select * from tempComputerSkillMap)

感谢所有答案的人,我猜两个表上的列应该是相同的,我的意思是两个都应该有一个id和skillName然后我们才能正确复制..感谢无论如何,

4 个答案:

答案 0 :(得分:1)

尝试进行类似

的查询
INSERT INTO candidateComputerSkillMapping (skillName)
SELECT skillName
FROM tempComputerSkillMap
WHERE candidateId=1;

或者

INSERT INTO candidateComputerSkillMapping
SELECT skillName
FROM tempComputerSkillMap
WHERE candidateId=1;

检查sqlauthority

如果candidateId表中的candidateComputerSkillMappingprimaryid,那么您无法将null插入主键并且会出错。这就是为什么要显示这两个表结构以获得良好答案

希望它有效。

答案 1 :(得分:0)

INSERT INTO [Table2] SELECT skillName FROM [skillmapping] WHERE candidateId = 1

答案 2 :(得分:0)

如果你认为数据已经存在,你需要更新它......

update Table2 set skillname = (select skillname from Table1 where candidateid =1)

如果您认为需要插入新记录,那么......

insert into Table2 select skillname from Table1 where candidateid = 1

答案 3 :(得分:0)

由于您的table2没有candidateid,我认为在插入时,您确信table2中包含的所有技能都属于candidateid = 1.

如果假设正确,那么您可以按照以下示例将table2中的新技能插入table1

编辑:使用评论更新了查询。

use tempdb

-- Pretending this is your table1
create table candidateComputerSkillMapping
(
    candidateid int             not null
    , skillname varchar(128)    not null
    , unique 
    (
        candidateid
        , skillname
    )
)

-- Table1 has one skill for candidateid = 1
insert candidateComputerSkillMapping values (1, 'Old Skill')

-- Prentending this is your table2
create table tempComputerSkillMap
(
    skillname varchar(128) not null
)

-- table2 has two skills. Now since this table doesn't have candidateid, how do I know the skills are for candidateid = 1?
-- I don't know and I am assuming that you are certain that these skills indeed belong to candidateid = 1.
insert tempComputerSkillMap values ('Old skill')
insert tempComputerSkillMap values ('New skill')

-- Insert only new skills from table2 into table1 for candidateid = 1
insert candidateComputerSkillMapping (candidateid, skillname)
select 1, t2.skillname
from tempComputerSkillMap t2
where not exists (select * from candidateComputerSkillMapping t1 where t1.candidateid = 1 and t1.skillname = t2.skillname)

select * from candidateComputerSkillMapping