Sunday, February 12, 2012

Changing Database Structures Through Code

I am having a hard time finding materials on this subject. I am guessing I am using the wrong keywords to search. Basically, I want to be able to modify database tables through a web form. They can add columns and delete columns through the form. I would just want to default the type of column and the length. I am sure it has been done, I was just wondering if anyone had some resources they could throw my way. I would appreciate it. Thanks.

Hi, I wrote a stored procedure to alter table, share with you:)

create proc sp_alterTbl @.TblName sysname,@.ColName sysname,@.ColType varchar(50)=null,
@.ColLen int=null,@.Op varchar(6)='Add'
as
begin
declare @.cmd varchar(500),@.TypeLenStr varchar(50)
if object_id(@.TblName) is null
Raiserror('Table does not exist!',16,1)
else
if not exists (select * from systypes where name= @.ColType)
Raiserror('Type does not exists!',16,1)
else
begin

select @.TypeLenStr=CASE @.ColLen WHEN null Then ' '
Else '('+convert(varchar(6),@.ColLen)+')'
END
select @.cmd= CASE @.Op when 'Add' Then 'alter table'+@.TblName+''+@.Op+''+@.ColName+' '
+@.ColType+ @.TypeLenStr
WHEN 'Drop' Then 'alter table'+@.TblName+''+@.Op+''+@.ColName+' '
END
EXEC(@.cmd)
END
END

No comments:

Post a Comment