复制数据库表

时间:2016-03-08 10:31:04

标签: sql sql-server sql-insert not-exists

我的这个表有多列。主键为(type,ref,code),行类型为t1t2,两个状态为有效(V)和无效(I)

状态t1中的每个无效行都应在状态t2中具有有效行, 但是我的表已经有一些处于无效状态的行,这些行在状态t2中没有有效行。

示例:

   type    |  ref   |  code   | state .....
----------------------------------------
   t1      |  1     | c1      | V
   t1      |  2     | c1      | V
   t1      |  3     | c1      | I
   t2      |  3     | c1      | V
   t1      |  4     | c1      | V
   t1      |  5     | c1      | I

所以我需要复制缺失的行

我正在使用

INSERT INTO table (type,ref,code,state)
SELECT 't2',ref,code,'V' FROM table
WHERE EXISTS (SELECT ref,code,count(*) from table GROUP BY ref,code HAVING count(*)=1)
AND state='I'

但我正在

 Violation of PRIMARY KEY

我试过

WHERE NOT EXISTS (SELECT ref,code,count(*) from table GROUP BY ref,code HAVING count(*)>1)
AND state='I'

并没有任何异议。任何dea如何执行这个?

3 个答案:

答案 0 :(得分:1)

如果它是主键,则必须是唯一的,并且对于定义不能为空。因此,如果您需要两个或更多状态,则需要另一个表或另一个字段(如果只有两个),而不是寻求查询

答案 1 :(得分:1)

您可以使用以下查询来获取要复制的行:

SELECT type, ref, code, state
FROM mytable AS t1
WHERE state = 'I' AND type = 't1' AND 
      NOT EXISTS (SELECT 1
                  FROM mytable AS t2
                  WHERE t1.ref = t2.ref AND t1.code = t2.code AND
                        state = 'V' AND type = 't2')

因此,INSERT语句可能如下所示:

INSERT INTO mytable 
SELECT 't2', ref, code, 'V'
FROM mytable AS t1
WHERE state = 'I' AND type = 't1' AND 
      NOT EXISTS (SELECT 1
                  FROM mytable AS t2
                  WHERE t1.ref = t2.ref AND t1.code = t2.code AND
                        state = 'V' AND type = 't2')

答案 2 :(得分:0)

试试这段代码。

  INSERT INTO #TAB
  SELECT 't2', REF, CODE, 'V' FROM #TAB WHERE stateS='I' 
  AND REF NOT IN (SELECT REF FROM #TAB WHERE stateS='V' AND typeSS='T2')