通过从另一个表复制单个列的单行来在一个表中插入记录

时间:2011-03-07 05:48:26

标签: c# .net sql sql-server sql-server-2005

我有一个表SEND,其中有一列Aname

Aname   
------
GREAME  
PETER   

另一个包含2列的表RECEIVE

Aname                              Permission
-----------------------------------------------
GREAME (copied from table SEND)    'my own value will be inserted here,
                                    specified in insert query'

PETER  (copied from table  SEND)    'my own value will be inserted here,
                                    specified in insert query'

现在,如上所示,我想在表RECEIVE中仅插入表Aname中的SEND列,并在第二列中插入新值。

另外,我希望在RECEIVE表中不能插入重复的值:

我想要这个:

Aname   Permission
---------------------
GREAME  PLAYER
GREAME  PLAYER --- COULD NOT BE INSERTED
GREAME  SALESMAN   --- COULD BE INSERTED

我正在使用此查询:

insert into receive(Aname, Permission)
  select Aname , 'Select' 
  from SEND
  where not exists
     (select * from RECEIVE where Aname = 'GREAME' and Permission = 'select')

此查询同时使用名称GREAME&来自SEND表的PETER并将它们插入到RECEIVE表中,但我希望只选择GREAME,而不是PETER。

我该怎么做?

从表SEND中取出所有行,并将它们插入到表RECEIVE中,但我希望只插入一行。所以我希望查询是这样的,但它给出了语法错误:

insert into RECEIVE(Aname , Permission)
  select Aname , 'select' 
  from SEND
  WHERE Aname = 'GREAME'  -------------this line gives error
  where not exists
    (select *  from RECEIVE where aname = 'GREAME' and Permission = 'select')

1 个答案:

答案 0 :(得分:3)

您不能在一个声明中包含两个WHERE子句

insert into RECEIVE(Aname , Permission)
  select Aname , 'select' 
  from SEND
  WHERE Aname = 'GREAME'   <=== WHERE #1
  where not exists         <=== WHERE #2
    (select *  from RECEIVE where aname = 'GREAME' and Permission = 'select')

您需要将第二部分更改为AND:

insert into RECEIVE(Aname , Permission)
  select Aname , 'select' 
  from SEND
  WHERE Aname = 'GREAME'  
  AND not exists
    (select *  from RECEIVE where aname = 'GREAME' and Permission = 'select')