我们在创建sqlserver得数据表的主键的时候,有时会出现,后面加一串随机字符串的情况,如图所示:
2.如果你有强迫症的话,可以使用以下sql脚本进行修改,将主键的名称修改为PK_表名.
--将表的主键名统一规范为PK_表名
DECLARE @PK_Name_Old varchar(100),@Table_Name varchar(100),@PK_Name_New varchar(100),@Col_Name varchar(100)
DECLARE Cursor_Update_Table_PK_Name CURSOR FOR
SELECT
a.name AS "tbl_name",
e.name AS "col_name",
b.name,
"PK_"+a.name as "new_pk_name"
FROM sysobjects AS a --对象表,结合a.xtype="U"条件,查用户表
LEFT JOIN sysobjects AS b --对象表,结合b.xtype="PK"条件,查主键约束
ON a.id=b.parent_obj
LEFT JOIN sysindexes AS c --索引表,根据(主键)约束名称匹配,查对应字段索引
ON a.id=c.id AND b.name=c.name
LEFT JOIN sysindexkeys AS d --索引中对应键、列的表,根据索引匹配,查字段id
ON a.id=d.id AND c.indid=d.indid
LEFT JOIN syscolumns AS e --字段表,根据字段id匹配,查字段名称
ON a.id=e.id AND d.colid=e.colid
WHERE a.xtype="U"
AND b.xtype="PK"
OPEN Cursor_Update_Table_PK_Name
FETCH NEXT FROM Cursor_Update_Table_PK_Name INTO @Table_Name,@Col_Name,@PK_Name_Old,@PK_Name_New
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ""+@Table_Name
-- 存在主键约束,则删除
--IF EXISTS(SELECT * FROM sysobjects WHERE name=@PK_Name_Old and xtype="PK")
Exec("Alter TABLE "+@Table_Name+" Drop Constraint "+@PK_Name_Old)
-- 重新添加主键约束
Exec("ALTER TABLE "+@Table_Name+" ADD CONSTRAINT "+@PK_Name_New+" PRIMARY KEY ("+@Col_Name+") ")
FETCH NEXT FROM Cursor_Update_Table_PK_Name INTO @Table_Name,@Col_Name,@PK_Name_Old,@PK_Name_New
END
CLOSE Cursor_Update_Table_PK_Name
DEALLOCATE Cursor_Update_Table_PK_Name
使用以上代码可以批量将表的主键名进行修改
你可以可以对以上脚本进行修改,比如批量给表的前面增加某个字符串,聪明的你肯定知道怎么做的。