Last active
December 18, 2015 05:39
-
-
Save yushiro/5734251 to your computer and use it in GitHub Desktop.
根据sql表中的数据, 生成insert into 语句
参考:http://blog.csdn.net/lee576/article/details/3511012
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if object_id('Z_SP_GenInsertSQL','p') is not null | |
drop proc Z_SP_GenInsertSQL | |
GO | |
create proc Z_SP_GenInsertSQL (@tablename varchar(256)) | |
as | |
begin | |
declare @sql varchar(max) | |
declare @sqlValues varchar(max) | |
set @sql =' (' + char(9) | |
set @sqlValues = 'values '+ char(9) + '(' + char(9) + '''+' | |
select @sqlValues = @sqlValues + cols + ' + '',' + char(9) + ''' + ' ,@sql = @sql + '[' + name + '],' + CHAR(9) | |
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,175) | |
then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+''''''''' + ' end' | |
when xtype in (231,239) | |
then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+''''''''' + ' end' | |
else '''NULL''' | |
end as Cols,name | |
from syscolumns | |
where id = object_id(@tablename) and autoval is null | |
) T | |
set @sql ='select ''INSERT INTO ' + CHAR(9) + '['+ @tablename + ']' + CHAR(9) + left(@sql,len(@sql)-2) + char(9) + ') ' + CHAR(9) + left(@sqlValues,len(@sqlValues)-6) + char(9) + ')'' from '+@tablename | |
print @sql | |
exec (@sql) | |
select 'SET IDENTITY_INSERT ['+@tablename+'] ON','SET IDENTITY_INSERT ['+@tablename+'] OFF' | |
/**//* | |
select * | |
from syscolumns | |
where id = object_id('test') and autoval is null | |
*/ | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment