Technical Article

spAddField

,

spAddField is the proc I use to add all fields to the db in our upgrade scripts.  With this proc, you pass it the tablename, fieldname, datatype, and null or not null.  This will call spGetFieldsExists and see if the fields exists or not.  If it does, spAddField will drop that column.  Then it readds it.  This allows me to execute a field add script over and over and not ever error because the field exists.  It drops the field, assuming that the new version is different. 
  Side effects of this is that the position of the field will change, if it exists already.  But usually its a new field, and its ok to run it over an over, since its adding it at the end anyway.

/**********************************************************
  spAddField
**********************************************************/
print 'spAddField'
go

if
  exists
  (
    select * from SysObjects
      where ID = Object_ID('spAddField')
        and ObjectProperty(ID, 'IsProcedure') = 1
  )
begin
  drop procedure spAddField
end
go

create procedure spAddField
  @TableName varchar(50),
  @FieldName varchar(50),
  @FieldType varchar(50),
  @Null varchar(50)
as
  set NoCount on
  --try

    declare 
      @result int,
      @execStr NVarChar(1024),
      @exists int

    exec @result = spGetFieldsExists @TableName, @FieldName, @exists output
    if @@Error <> 0 or @Result <> 0 goto ErrorProc

    if ( @exists = 1 )
    begin
      select @execStr =
      'alter table ' + @TableName +
      '  drop column ' + @FieldName 

      exec @Result = sp_executesql @execStr
      if @@Error <> 0 or @Result <> 0 goto ErrorProc

      set @exists = 0      
    end

    if ( @exists = 0 )
    begin
      select @execStr =
      'alter table ' + @TableName +
      '  add ' + @FieldName + ' ' + @FieldType + ' ' + @Null

      exec @Result = sp_executesql @execStr
      if @@Error <> 0 or @Result <> 0 goto ErrorProc
    end


  --finally
    SuccessProc:
    return 0  /* success */
  --except
    ErrorProc:
    return 1 /* failure */
  --end
go

grant execute on spAddField to Public
go

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating