sqlserver+mysql 添加字段判斷是否存在(存在不添加)

-- mzj 2019-09-18 貸後監控設置sql語句
-- sqlServer版本
-- 刪除存儲過程
if exists (select * from dbo.sysobjects where id = object_id(N'pro_AddColum') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
	drop procedure pro_AddColum;
END
GO

CREATE PROCEDURE pro_AddColum
@tableName VARCHAR ( 80 ),
@columnName VARCHAR ( 80 ),
@columnsType VARCHAR ( 80 ),
@descriptionStr VARCHAR( 80 )
AS 
BEGIN
	declare @sqlStr NVARCHAR (3000);
	if @tableName is not null   and  @tableName!='' and @columnName is not null  and @columnName!='' and @columnsType is not null  and @columnsType!='' 
	begin
		if col_length(@tableName,@columnName) is null
		begin
			set @sqlStr= 'ALTER TABLE ' + @tableName + ' ADD ' + @columnName + ' ' + @columnsType + ';';
			exec(@sqlStr);
			execute sp_addextendedproperty 'MS_Description',@descriptionStr,'user','dbo','table',@tableName,'column',@columnName;
		end
	end 
END 
GO

-- 調用
	EXEC pro_AddColum '表名','字段名稱','字段名稱','備註';
-- 刪除存儲過程
drop procedure pro_AddColum;
-- mzj mysql版本
-- 刪除存儲過程
delimiter //
 drop procedure if exists pro_AddColum;
//
-- 創建存儲過程
delimiter //
create procedure pro_AddColum(in tableName varchar(80),in columnName varchar(80),in columnsType varchar(80),in descriptionStr varchar(80))
begin
	if tableName is not null   and  tableName!='' and columnName is not null  and columnName!='' and columnsType is not null  and columnsType!='' then
			if not EXISTS(select 1 from information_schema.columns where table_schema=DATABASE() and table_name=tableName and column_name=columnName)then 
					set @sqlStr=CONCAT('alter table ',tableName,' add ',columnName,' ',columnsType,' DEFAULT NULL COMMENT \'',descriptionStr,'\'');
					prepare stmt from @sqlStr;
					execute stmt;
		end if;
	end if;
end;
//
-- 調用
	delimiter //
	call pro_AddColum('表名','字段名稱','字段名稱','備註');
	//
-- 刪除存儲過程
delimiter //
 drop procedure if exists pro_AddColum;
//

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章