---
title: "Oracle比较相似结构的两套表"
author: "coder"
date: "2012-12-04T20:24:21Z"
tags: []
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2012-12-04T21:14:58Z"
id: 1741121
url: "https://coder.iteye.com/blog/1741121"
---

出于某些原因，需要建立几十张表，使用DEL\_开头，用于数据清理时记录所清理的数据。比如表TABLE1就对应DEL\_TABLE1，但不幸的是，PDM文件与正式库表存在不一致，造成insert into DEL\_TABLE1 select * from TABLE1未能正确插入，因此，有必要比较DEL\_开头的表和对应表的差异。

写程序太麻烦了，还是用SQL吧：

1、比较字段

```
select * from cols t where table_name like 'DEL%'
and not exists (select 1 from cols t1
      where t1.TABLE_NAME=substr(t.TABLE_NAME, 5)
      and t1.COLUMN_NAME=t.COLUMN_NAME
      and t1.DATA_TYPE=t.DATA_TYPE
      and t1.DATA_LENGTH=t.DATA_LENGTH
      and t1.COLUMN_ID=t.COLUMN_ID
      and t1.NULLABLE=t.NULLABLE)
```

 

2、检查是否有新字段

```
select * from cols t
where exists (select 1 from cols t2 where t2.table_name = 'DEL_'||t.table_name)
and not exists (select 1 from cols t1
      where t1.table_name = 'DEL_'||t.table_name
      and t1.COLUMN_NAME=t.COLUMN_NAME)
```