分类目录

链接

2012年 4月
 1
2345678
9101112131415
16171819202122
23242526272829
30  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > SQL Server > 正文
sql server联合主键/复合主键查询
SQL Server 评论(1) 阅读(9,158)

sql server联合主键/复合主键的数据库表,在另一个数据库表是否存在的SQL查询语名

--如果是只有一个主键的话,就使用主键 not In 、主键 In 来写SQL脚本,很简单就不多说了。
--那联合主键的表又怎么处理呢,其实也很简单,使用Not exists 、exists ,以前还真不知道 exists 还有此用法
--看下面的例子,表@A(字段j,字段n为联合主键),表@B(字段j,字段n为联合主键)

--如果是只有一个主键的话,就使用主键 not In 、主键 In 来写SQL脚本,很简单就不多说了。 --那联合主键的表又怎么处理呢,其实也很简单,使用Not exists 、exists ,以前还真不知道 exists 还有此用法 --看下面的例子,表@A(字段j,字段n为联合主键),表@B(字段j,字段n为联合主键)
declare @A table (i int,j int ,n varchar(50) primary key(j,n)) declare @B table (i int,j int ,n varchar(50) primary key(j,n)) insert @A(i,j,n) select 1,1,'a' 
union all select 2,1,'b'
union all select 3,1,'c'
union all select 4,1,'d'
union all select 5,1,'e'
union all select 6,2,'a'
union all select 7,2,'b'
union all select 8,2,'c'
union all select 9,2,'d'
union all select 10,2,'e'

insert @B(i,j,n) select 1,1,'a' 
union all select 2,1,'b'
union all select 3,1,'c'
union all select 4,2,'a'
union all select 5,2,'b'
union all select 6,2,'c'

--跟据主键,查询@A表有的,@B没有的
select * from @A a where not exists( select * from @B b where a.j=b.j and a.n=b.n ) --也可批量删除@A ,跟据主键,@A表有的,@B没有的
delete a from @A a where not exists( select * from @B b where a.j=b.j and a.n=b.n ) --跟据主键,查询@A表有的,@B也有的
select * from @A a where exists( select * from @B b where a.j=b.j and a.n=b.n )
复制代码

 

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:sql server联合主键/复合主键查询 | Bruce's Blog

sql server联合主键/复合主键查询:目前有1 条留言

  1. : 2012年04月26日上午 11:36 回复

    找了好久才找到~谢谢博主,超感动!吼吼~~

发表评论

留言无头像?