插入到sql db(没有重复)

时间:2015-10-20 06:56:17

标签: sql insert duplicates

将数据插入数据库时​​遇到了问题。我想知道如何只添加表中尚未存在的数据?

INSERT  INTO dbo.Posta
    (
        DrzavaID,
        PostnaStevilka,
        Naziv,
        record_dt_modified,
        record_modifier_id,
        record_dt_created,
        record_creator_id
    )

    select 
        d.DrzavaID,
        p.PostnaSt, 
        concat(CONCAT(p.Provinca,+' - '+p.Okrozje),+' - '+p.Mesto),
        @record_dt_modified,
        @record_modifier_id,
        @record_dt_modified,
        @record_modifier_id
    FROM mmdb_kopijaSI.dbo.Drzava d,#PostaT p
    WHERE d.Kratica='TR';
alter PROCEDURE addPosta 
AS
BEGIN
insert into #PostaT values( 'ADANA','ALADA?(KARSANTI)','AKÖREN',1720 );
insert into #PostaT values( 'ADANA','ALADA?(KARSANTI)','KARSANTI',1720 );
insert into #PostaT values( 'ADANA','ALADA?(KARSANTI)','MERKEZKÖYLER',1720 );
insert into #PostaT values( 'ADANA','CEYHAN','B?RKENT',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','BÜYÜKMANGIT',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','CEYHAN',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','DORUK',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','EMEK',1940 );
insert into #PostaT values( 'ADANA','CEYHAN','HAMD?LL?',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','KÖSREL?',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','KURTKULA?I',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','KURTPINAR',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','MERC?MEK',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','MERKEZKÖYLER',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','MUSTAFABEYL?',1920 );
insert into #PostaT values( 'ADANA','CEYHAN','NAMIKKEMAL',1950 );

。 .. ...到10000个插入

CREATE TABLE #PostaT
    (
        Provinca varchar(20),
        Okrozje varchar(20),
        Mesto varchar(20),
        PostnaSt int
    )

    exec [PosteZaPoseg];

我用大约10000件物品的程序填写我的表格。我想用表[

中没有的过程[PosteZaPoseg]的数据填充表格

2 个答案:

答案 0 :(得分:0)

您必须检查表格上的数据

试试这个

 IF NOT EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
        INSERT INTO Table1 VALUES (...)
    ELSE
        UPDATE Table1 SET (...) WHERE Column1='SomeValue'

答案 1 :(得分:0)

你可以这样做:

INSERT  INTO dbo.Posta
       (DrzavaID
       , PostnaStevilka
       , Naziv
       , record_dt_modified
       , record_modifier_id
       , record_dt_created
       , record_creator_id
        )
SELECT  d.DrzavaID
      , p.PostnaSt
      , CONCAT(CONCAT(p.Provinca, +' - ' + p.Okrozje), +' - ' + p.Mesto)
      , @record_dt_modified
      , @record_modifier_id
      , @record_dt_modified
      , @record_modifier_id
FROM    mmdb_kopijaSI.dbo.Drzava d
      , #PostaT p
LEFT JOIN   dbo.Posta q
    ON      q.keyfld  = p.keyfld
WHERE   d.Kratica = 'TR'
    AND q.keyfld IS NULL;

我假设你在Posta和#Posta表上有一个唯一的密钥(我为它起了假名keyfld。)

此外,您是否知道您正在创建一个carthesian产品,因为您没有直接将Drzava表连接到#PostaT表?