zoukankan      html  css  js  c++  java
  • 将表里的数据批量生成INSERT语句的存储过程

    有时候,我们需要将某个表里的数据全部导出来,迁移到另一个相同结构的库中,这里可以采取一个简便的方法,通过一个存储过程批量导出数据并生成SQL语句,非常方便。存储过程如下:

    CREATE   proc [dbo].[spGenInsertSQL] (@tablename varchar(256))
    as
    begin
    declare @sql varchar(max)
    declare @sqlValues varchar(max)
    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)
    end
    
    
    
    GO
  • 相关阅读:
    C++ 类型别名typedef和using
    网页布局及响应式
    js上传图片预览
    bootstrap中-webkit-text-size-adjust :not()
    开始
    通过setDB2Client*来方便的使用TRACE调优jdbc程序
    关于携程的信息泄漏
    如何设置DB2I(SPUFI)来正常工作
    Limit the query running time with Resource limit facility (RLF)
    z/os上的tar和gzip(3)
  • 原文地址:https://www.cnblogs.com/NichkChang/p/4277705.html
Copyright © 2011-2022 走看看