SQLServer使用存储过程增加列

--将添加一列写成存储过程
--if exists(select * from sysobjects where id=object_id(N['addcol']) and objectproperty (id,N'isProcedure')=1)
IF  EXISTS (  SELECT  * FROM SYS.OBJECTS WHERE TYPE='P' AND NAME='addcol' )
begin
print '存在这个存储过程';
drop procedure addcol;
end;
go
create procedure addcol ( @tablename varchar(15),@colname varchar (15),@coltype varchar(20))
as
begin
declare @sql varchar(300);---要执行添加列的sql语句
if not exists(select * from syscolumns where id=object_id(@tablename) and name=@colname)
    begin
    set @sql='ALTER TABLE '+@tablename+' '+'ADD '+ @colname+' '+@coltype +' DEFAULT 2 NOT NULL';
    print  @sql;
    --ALTER TABLE @tablename ADD @colname @coltype DEFAULT 2 NOT NULL;
    exec (@sql);----!!!!一定要带括号!!!
    end;
end;
Go
--调用存储过程以下几种都可以
execute addcol 'test2','test2id','int'; 

猜你喜欢

转载自blog.csdn.net/upi2u/article/details/85725131
今日推荐