sql 批量操作添加/ 删除 表主键
直接上代码把: 是存储过程哦 ,
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[prc_name] (
@nameinfo nvarchar(50) output
)
AS
declare @Key NVARCHAR(MAX) --创建参数 返回创建主键
declare @tab NVARCHAR(MAX) --创建参数 返回 表
declare @tabs NVARCHAR(MAX) --创建参数 返回 表
IF
EXISTS(SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE [email protected])
BEGIN
set @Key=(SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE [email protected])
SET @tab=(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE [email protected])
PRINT(‘表‘[email protected]+‘存在主键名为:‘[email protected])
END
ELSE
BEGIN
SET @tabs=(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE [email protected])
declare @b NVARCHAR(MAX) --创建参数 返回 表
declare @name NVARCHAR(MAX)
SET @name=‘BPMID‘
set @b=‘ALTER TABLE ‘[email protected]+‘ ADD ‘[email protected]+‘ INT IDENTITY(1,1) PRIMARY KEY‘;
exec SP_EXECUTESQL @b
PRINT(‘添加主键成功‘)
END
--------------添加 主键
exec prc_name‘a‘
exec prc_name‘b‘
------- 批量删除 主键 存储过程
------删除主键
ALTER TABLE a DROP COLUMN BPMID; -- -- 删除表字段
alter table a drop constraint PK_b -- 删除主键约束
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME=‘b‘ --获取主键
go
if exists(select*from sysobjects where name=‘proc_k‘)
drop procedure proc_k
go
create proc proc_k (
@name nvarchar(50)
)
AS
declare @SNAME NVARCHAR(MAX)
set @SNAME=(
SELECT B.NAME AS 主键名`
FROM SYSOBJECTS A
JOIN SYSOBJECTS B
ON A.ID=B.PARENT_OBJ
AND A.XTYPE=‘U‘ AND B.XTYPE=‘PK‘
and A.NAME in (@name)
)
declare @key NVARCHAR(MAX) --获取主键
set @key=(SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE [email protected])--获取 主键名
declare @a NVARCHAR(MAX) --先删除 主键约束
set @a=‘alter table ‘[email protected]+‘ drop constraint ‘[email protected]+‘‘
exec SP_EXECUTESQL @a --执行
--再删除表
declare @b NVARCHAR(MAX)
SET @b= ‘ALTER TABLE ‘[email protected]+‘ DROP COLUMN ‘[email protected]+‘‘ -- -- 删除主键字段
exec SP_EXECUTESQL @b
PRINT(‘删除主键成功‘)
---------- 删除主键----------
go
exec proc_k‘a‘
exec proc_k‘b‘
原文地址:https://www.cnblogs.com/zonzi/p/12583167.html