在SQL Server中的两个表之间获取不同的列名称

时间:2017-03-29 17:04:59

标签: sql sql-server

在我的SQL Server数据库中,我在不同的模式中具有相同的表名。例如schema1.card(表1)和schema2.card(表2)。

我的数据库中有大约40个表。我只想比较两个表,并想知道这两个表之间的不同列名

我附上了表格的截图。我想找出表2中没有但存在于表1中的所有列,反之亦然。

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以使用Information_schema或sys.columns

select * from information_schema.columns where table_name = 'card' and table_schema = 'schema1'
except
select * from information_schema.columns where table_name = 'card' and table_schema = 'schema2'

- 完全加入

select * from information_schema.columns t1
full join information_schema.columns t2 
on t1.table_catalog=t2.table_catalog
and t1.column_name = t2.column_name
where
t1.table_name = 'card' and t2.table_name = 'card'
and t1.table_schema = 'schema1' and t2.table_schema = 'schema2'
and (t1.column_name is null or t2.column_name is null)

答案 1 :(得分:0)

select Column_Name from information_schema.columns where table_name = 'sysjobs' and table_schema = 'YourSchema1'
except
select Column_Name from information_schema.columns where table_name = 'sysjobservers' and table_schema = 'YourSchema2'

此外,您可以做的是创建一个变量并遍历所有模式并将差异放在临时表中。这样你就不必一个一个地做,你可以自动化它

答案 2 :(得分:0)

我尝试在我的第二个架构中添加一个列并编写以下查询adn我得到了我想要的输出。

    select * from information_schema.columns t1 where t1.table_name = 'card' and   t1.table_schema = 'Custom' and 
t1.column_name not in(select t2.column_name from information_schema.columns t2 where  t2.table_name = 'card' and   t2.table_schema = 'boston' )