Friday, June 20, 2014

TO GENERATE AUTOMATIC INSERT PROCEDURE BY USING THIS PROCEDURE

by using this procedure to print insert procedure to table:


create proc usp_tablecolumns(@tablename varchar(20))
as
--usp_tablecolumns 'emp'
begin
declare @column_parameters varchar(1000)='' 
declare @columns varchar(1000)='' 

declare @cname varchar(100)=''
select @column_parameters=@column_parameters + ',@'+s.name + ' ' + c.name+ case when c.name in( 'int','money','datetime') then '' else ' ('+cast (s.max_length as varchar(10))+')' end
, @columns = @columns + ',@' + s.name
from sys.columns as s
inner join sys.types c 
on  s.system_type_id=c.system_type_id where object_id=OBJECT_ID(@tablename)
    and s.is_identity = 0
print 'CREATE PROC usp_insert_'+@tablename + '('+ right(@column_parameters,len(@column_parameters)-1) + ') as'
print 'BEGIN'
print ' insert into ' + @tablename + ' ' + ' values ('+ @columns+')'
PRINT 'END'
end
exec usp_tablecolumns @tablename='emp'
e


select  * from sys.columns 
select * from sys.types

No comments:

Post a Comment