Chào các bạn,
Đối với các bạn phát triển phần mềm, mỗi khi tạo một table mới và dùng store procedure chúng ta thường phải code store procedure insert, update, delete bằng tay. Đoạn script bên dưới khi chạy sẽ tự động tạo script store insert, các bạn có thể copy câu script sinh ra và create store
Mình xin giới thiệu đoạn code tự động sinh ra câu lệnh TSQL để chúng ta đỡ tốn thời gian code. Câu lệnh còn đơn giản chưa lường trước được một số trường hợp, các bạn đóng góp thêm.
/*===================================================================================*/
/*tạo store procedure insert động*/
declare @tableName nvarchar(100) = ‘Roles’ /*Nhập tên table cần tạo store insert*/
/*===================================================================================*/
declare @sql nvarchar(max)=”
select object_id, name, column_id, user_type_id, max_length, ” as ‘TypeName’ into #table from sys.all_columns
where object_id =OBJECT_ID(@tableName)
set @sql=@sql+’create procedure [sp_’+ @tableName + ‘_Insert]’ + char(13)
declare @tempsql nvarchar(max)=”
select @tempsql=@tempsql + ‘@’+ b.name + ‘ ‘ + a.name +
case a.name
when ‘datetime’
then ‘,’ + char(13)
when ‘bigint’
then ‘,’ + char(13)
when ‘bit’
then ‘,’ + char(13)
when ‘date’
then ‘,’ + char(13)
when ‘float’
then ‘,’ + char(13)
when ‘image’
then ‘,’ + char(13)
when ‘int’
then ‘,’ + char(13)
when ‘ntext’
then ‘,’ + char(13)
when ‘real’
then ‘,’ + char(13)
when ‘smallint’
then ‘,’ + char(13)
when ‘text’
then ‘,’ + char(13)
when ‘uniqueidentifier’
then ‘,’ + char(13)
when ‘tinyint’
then ‘,’ + char(13)
when ‘smalldatetime’
then ‘,’ + char(13)
when ‘smallmoney’
then ‘,’ + char(13)
when ‘sql_variant’
then ‘,’ + char(13)
else
‘(‘ + CONVERT(nvarchar, b.max_length) +’),’ + char(13)
end from sys.types a join #table b on a.user_type_id=b.user_type_id
set @tempsql = SUBSTRING(@tempsql, 0, len(@tempsql)-1)+char(13)
set @sql= @sql + @tempsql+’as’ + char(13)
set @sql=@sql+’insert into [‘+ @tableName+’](‘
set @tempsql = ”
select @tempsql=@tempsql+'[‘+name+’],’ from #table
set @tempsql= RTRIM(LTRIM(@tempsql))
set @tempsql = SUBSTRING(@tempsql, 0, len(@tempsql))
set @sql=@sql+@tempsql + ‘)’ + char(13)
set @sql =@sql+’values(‘
set @tempsql=”
select @tempsql=@tempsql+’@’+name + ‘,’ from #table
set @tempsql = SUBSTRING(@tempsql, 0, len(@tempsql))
set @sql=@sql+@tempsql + ‘)’ + char(13)
print @sql
drop table #table