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
  • 相关阅读:
    为什么你SQL Server的数据库文件的Date modified没有变化呢?
    SQL Server中SELECT会真的阻塞SELECT吗?
    ORACLE从共享池删除指定SQL的执行计划
    flink DataStream API使用及原理
    漫谈九品中正制和现阶段阶层分层
    flink dataset api使用及原理
    从flink-example分析flink组件(3)WordCount 流式实战及源码分析
    TODO supply a title
    avalon2学习教程01
    avalon1与avalon2的异同点
  • 原文地址:https://www.cnblogs.com/NichkChang/p/4277705.html
Copyright © 2011-2022 走看看