The SQL-DMO object library has a Script method for pretty much every object in SQL Server. There are code examples in Books Online under "Building SQL Server Applications, SQL-DMO". Since it's a COM library you could use sp_OACreate and such to run these methods from a T-SQL stored procedure.