根據表中資料生成insert語句的儲存過程

2021-03-31 08:57:00 字數 1821 閱讀 6954

有個缺點……就是標識種子的列 也insert了

create   proc spgeninsertsql (@tablename varchar(256))

asbegin

declare @sql varchar(8000)

declare @sqlvalues varchar(8000)

set @sql =' ('

set @sqlvalues = 'values (''+'

select @sqlvalues = @sqlvalues + cols + ' + '','' + ' ,@sql = @sql + '[' + name + '],'

from

(select case

when xtype in (48,52,56,59,60,62,104,106,108,122,127)                               

then 'case when '+ name +' is null then ''null'' else ' + 'cast('+ name + ' as varchar)'+' end'

when xtype in (58,61)

then 'case when '+ name +' is null then ''null'' else '+''''''''' + ' + 'cast('+ name +' as varchar)'+ '+'''''''''+' end'

when xtype in (167)

then 'case when '+ name +' is null then ''null'' else '+''''''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'

when xtype in (231)

then 'case when '+ name +' is null then ''null'' else '+'''n'''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'

when xtype in (175)

then 'case when '+ name +' is null then ''null'' else '+''''''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as char(' + cast(length as varchar)  + '))+'''''''''+' end'

when xtype in (239)

then 'case when '+ name +' is null then ''null'' else '+'''n'''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as char(' + cast(length as varchar)  + '))+'''''''''+' end'

else '''null'''

end as cols,name

from syscolumns 

where id = object_id(@tablename)

) t

set @sql ='select ''insert into ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlvalues,len(@sqlvalues)-4) + ')'' from '+@tablename

--print @sql

exec (@sql)

endgo

根據表中資料生成insert語句的儲存過程

根據表中資料生成insert語句的儲存過程 alter proc proc insert tablename varchar 256 wherestr nvarchar 1000 as 表名稱 begin set nocount on declare sqlstr varchar 4000 sqls...

將表中的資料生成INSERT語句

create procedure dbo outputdata tablename varchar 100 表名 asdeclare isidentity int declare columnname varchar 100 列名 declare typename varchar 100 資料型別 ...

SQLServer 匯出資料insert語句

set nocount on 表名和查詢條件 declare tablename varchar 64 c varchar 512 set tablename ba roleauthority set c where 1 1 定義欄位名,型別和長度的變數,以及獲取表結構的游標 declare nam...