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
  • 相关阅读:
    NCD 2019 M. NCD Salary
    NCD 2019 H. Mr. Hamra and his quantum particles
    Codeforces Testing Round #16 C.Skier
    序列自动机(数组)
    Codeforces #640 div4 F~G (构造二连弹)
    NCD 2019 C. Hasan and his lazy students
    欧拉定理,费马小定理
    微信开发
    异常后显示错误页面
    js窗体间传值
  • 原文地址:https://www.cnblogs.com/NichkChang/p/4277705.html
Copyright © 2011-2022 走看看