如果1个字段不同,如何将多个值插入行

时间:2013-08-16 11:07:07

标签: sql sql-server sql-server-2008

是的,我需要将以下数据插入到名为locals的表中,但我只想在locals表中不存在street字段时插入它。数据和字段如下:

Street    PC       Locality
------------------------------
Street1   ABC xyz  A
Street2   DEF xyz  B

依此类推,但如果当地人表中尚未出现街道字段,我想插入本地人表。

我在考虑使用以下内容:

INSERT
  INTO Locals (Street,PC,Locality) 
       (
            SELECT DISTINCT s.Street
              FROM Locals_bk s
             WHERE NOT EXISTS (
                      SELECT 1
                        FROM Locals l
                       WHERE s.Street = l.Street
                   )
       )
     ;

但我意识到只会在同一行插入街道字段而不是其他数据。

4 个答案:

答案 0 :(得分:3)

insert into Locals (Street, PC, Locality) 
select b.Street, b.PC, b.Locality
from Locals_bk as b
where not exists (select * from Locals as t where t.street = b.street)

insert into Locals (Street, PC, Locality) 
select b.Street, b.PC, b.Locality
from Locals_bk as b
where b.street not in (select t.street from Locals as t)

答案 1 :(得分:1)

怎么样

INSERT [Locals]
SELECT
            [Street],
            [PC],
            [Locality]
    FROM
            [Locals_bk] bk
    WHERE
         NOT EXIST (
             SELECT * FROM [Locals] l WHERE l.[Street] = bk.[Street]
         );

答案 2 :(得分:1)

您可以使用NOT IN:

    INSERT into Locals (Street,PC,Locality) 
    SELECT s.Street, s.PC, s.Locality
    FROM Locals_bk as s
    WHERE NOT IN (SELECT * FROM Locals as t WHERE t.street = s.street)

答案 3 :(得分:0)

以下内容从与街道匹配的任意行中提取所需字段:

insert into Locals (Street, PC, Locality) 
select s.Street, s.PC, s.Locality
from (select s.*, row_number() over (partition by s.Street order by (select NULL)) as seqnum
      from Locals_bk s
     ) s
where seqnum = 1 and
     NOT EXISTS (SELECT 1
                  FROM Locals l
                  WHERE s.Street = l.Street);

如果您知道值始终相同,则可以执行以下操作:

insert into Locals (Street, PC, Locality) 
select distinct s.Street, s.PC, s.Locality
from Locals_bk s
where NOT EXISTS (SELECT 1
                  FROM Locals l
                  WHERE s.Street = l.Street);