数据库表中的主键能不能修改?

数据库表中的主键能不能修改?,第1张

可以修改,可以一般不会去修改。因为主键是数据表中的唯一标识符,不是所有的字段都可以用来当主键的。所以一般不会去修改它。一般的方法是先删除主键约束,然后再重新添加。alter table 表名 drop constraint 主键名修改主键:alter table 表名 add constraint 主键名 primary key (column1,column2,....,column)

如果每次要更新多行,那必须还要有一个唯一索引来定位要修改的记录,比如为Col_Uq,那可以如下写触发器:

create

trigger

tri_update_tb_1_pk

on

tb_1

for

update

as

if

not

update(col_pk)

return

update

tb_2

set

col_pk=i.col_pk

from

tb_2,inserted

i,deleted

d

where

tb_2.col_pk=d.col_pk

and

i.Col_Uq=d.Col_Uq

go

如果保证每次只更新一行,那可以如下写触发器:

create

trigger

tri_update_tb_1_pk

on

tb_1

for

update

as

if

not

update(col_pk)

return

if

(select

count(*)

from

inserted)>

1

return

update

tb_2

set

col_pk=i.col_pk

from

tb_2,inserted

i,deleted

d

where

tb_2.col_pk=d.col_pk

go


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/sjk/6464891.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-22
下一篇 2023-03-22

发表评论

登录后才能评论

评论列表(0条)

保存