關於主鍵操作

zhangguiyou 2008-05-24 09:49:43
在sql裡如何查詢某一個表的主鍵是否存在?
如何修改主鍵?
刪除主鍵?
高手請回答!
...全文
70 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangguiyou 2008-05-24
  • 打赏
  • 举报
回复
謝謝。
wzy_love_sly 2008-05-24
  • 打赏
  • 举报
回复
if(select objectproperty(object_id(name),'IsPrimaryKey') from sysindexes where object_id('tb')=id)=1
print '有主键'
else
print '没主键'
zhangguiyou 2008-05-24
  • 打赏
  • 举报
回复
那如何可以判斷主鍵是否存在呢?
  • 打赏
  • 举报
回复
如何修改主鍵?
--修改主键的值:如果该主键没有被其他的表引用,使用update语句进行修改
如果被其他的表引用,那么就需要使用触发器来进行了,在修改了主键的值后还要修改引用该主键的表中的值
--修改表的主键的话:在表的设计器里面来进行修改比较简单。也可以先去掉原来的主键约束,然后再建立新的主键约束
刪除主鍵?
方法同修改主键
wzy_love_sly 2008-05-24
  • 打赏
  • 举报
回复
create table tp(id int primary key)

exec sp_helpconstraint tp


tp


PRIMARY KEY (clustered) PK__tp__7C8480AE (n/a) (n/a) (n/a) (n/a) id
wzy_love_sly 2008-05-24
  • 打赏
  • 举报
回复
--drop table index_tb
create table index_tb(id int constraint ck_id default 0,name varchar(20),xb varchar(2))
--查看表
exec sp_helpindex orders--索引
exec sp_helpconstraint index_tb --约束
exec sp_fkeys 'dbo.Person'--外键
--键不唯一,非聚集索引
create index id_index on index_tb(id)
--删除索引
drop index index_tb.id_index
--键聚集索引
create clustered index id_index on index_tb(id)
--删除索引
drop index index_tb.id_index
--创建check约束
alter table index_tb add constraint ck_index CHECK (name like '[0-9][0-9][0-9][0-9][0-9]')
alter table index_tb add constraint ck2_index check(xb in ('MM','GG'))
--删除check约束
alter table index_tb drop constraint ck2_index
--禁止表约束
alter table index_tb nocheck constraint ck_index
--恢复表约束
alter table index_tb check constraint ck_index
--禁止和恢复所有check-all关键字
select 'alter table '+name+' nocheck or check constraint all' from sysobjects where type='U'
--添加新默认值和约束
ALTER TABLE index_tb ADD CONSTRAINT de_name DEFAULT ('11111') FOR name
--删除表约束
alter table index_tb drop constraint de_name
-- 字段 UNIQUE NOT NULL = PRIMARY KEY 差不多
--创建unique
alter table index_tb add constraint uniqueindex unique(id)
--删除unique
alter table index_tb drop constraint uniqueindex

insert into index_tb(name,xb) select '12345','mm'

select * from index_tb

delete index_tb

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧