1. 程式人生 > >SQLServer(語法二)————新增一列(T_SQL+儲存過程)

SQLServer(語法二)————新增一列(T_SQL+儲存過程)

  • 判斷列是否存在                                                                                                                                                                               
    語法:if exists(select * from syscolumns where id=object_id('表名') and name='列名')  
  • 判斷儲存過程是否存在

if exists (select * from sysobjects where id = object_id(N'[儲存過程名]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)  

  drop procedure [儲存過程名]

IF  EXISTS (  SELECT  * FROM SYS.OBJECTS WHERE TYPE='P' AND NAME='

儲存過程名' )

--方法一增加一列
--if not exists(select * from syscolumns where id='test2' and name='name')
if not exists(select * from syscolumns where id=object_id('test2') and name='testid')
begin  
print '123';
select * from test2;
ALTER TABLE test2 ADD testid INT DEFAULT 1 NOT NULL;
end;
go
--select * from test2;
---方法二判斷列是否存在
if col_length('test2','name') is null
	print 'not exists'
else
	print 'exists'
go
--將新增一列寫成儲存過程
--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 
[email protected]
) begin set @sql='ALTER TABLE '[email protected]+' '+'ADD '+ @colname+' '[email protected] +' 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'; --exec [addcol] 'test2','test3id','int'; --exec addcol 'test2','test4id','int';