如何用SQL获取一个表的主键的名字,谢谢
如表名为:Customer
主要作用是把Customer中和表Customer1中数据一样的行删掉
sp_help p_spinfo
sp_helpindex p_spinfo
delete a from Customer a,Customer1 b where a.主建=b.主建。
select * from sysobjects where name like pk__%
或者使用系统存储过程:
exec sp_helpconstraint Customer
哦,不明白,楼主的意思啦,
得到主键的名字,
是把Customer中和表Customer1中数据一样的行删掉
要想把两个表中的一样的数据删除掉,只要表连接不就可以
找到一样的数据吗,不就可以删除了吗?
解释一下:
exec sp_helpconstraint Customer
这句的意思是利用系统存储过程,查询 Customer上约束的定义
因为每一个表中有且只有一个主键。
http://community.csdn.net/Expert/icView.asp?id=4186660
select
d.name
from
sysindexes a,
sysobjects b,
sysindexkeys c,
syscolumns d
where
c.id = object_id(t1) --替换成相应的表名
and
c.id = b.parent_obj
and
a.name = b.name
and
b.xtype=PK
and
a.indid = 1
and
d.colid = c.colid
and
d.id = c.id
楼上的查出来好象不对啊。
create table #primary
(
a sysname,
b sysname,
c sysname,
d sysname,
e int,
f sysname
)
insert #primary exec sp_pkeys t_pcdmx
#primary中的d列就要楼住要的吧??
--得到主键字段名
1:
SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME<>dtproperties
2:
EXEC sp_pkeys @table_name=表名
3:
select o.name as 表名,c.name as 字段名,k.colid as 字段序号,k.keyno as 索引顺序,t.name as 类型
from sysindexes i
join sysindexkeys k on i.id = k.id and i.indid = k.indid
join sysobjects o on i.id = o.id
join syscolumns c on i.id=c.id and k.colid = c.colid
join systypes t on c.xusertype=t.xusertype
where o.xtype = U
and o.name=要查询的表名
and exists(select 1 from sysobjects where xtype = PK and parent_obj=i.id and name = i.name)
order by o.name,k.colid
--测试数据
use northwind
go
select * into orders2 from orders
--示例
declare @where varchar(1000), @str varchar(2000)
set @str=
delete orders2
where exists(select 1
from orders as tt
set @where=
select @where=@where+ and [+name+]=tt.[+name+]
from syscolumns where id=object_id(orders)
select @where= where +substring(@where, 5, len(@where))+)
set @str=@str+@where
print @str --你看看sql语句就知道我在做什么了。
exec (@str)
--查询删除后的结果
select * from orders2
--清除
drop table orders2
使用系统存储过程:exec sp_pkeys 表名
厉害厉害....收藏收藏....