文章继续 桦仔兄的文章 将表里的数据批量生成INSERT语句的存储过程 增强版 继续增强...

本来打算将该内容回复于桦仔兄的文章的下面的,但是不知为何博客园就是不让提交!....

所以在这里贴出来吧,算作继续增加文章中解决的:根据查询条件自动生成插入脚本的需求,其实这种需求还是蛮常见的。

本文着重解决了文中的脚本的schema问题,给调整了下,现在脚本能自动识别出不同的schema下同名的表的语句

修改后脚本如下:

-- Author:      <桦仔>
-- Blog: <http://www.cnblogs.com/lyhabc/>
-- Create date: <2014/10/18>
-- Description: <根据查询条件导出表数据的insert脚本>
-- =============================================
ALTER PROCEDURE InsertGenerator
(
@tableName NVARCHAR(MAX),
@whereClause NVARCHAR(MAX)
)
AS --Then it includes a cursor to fetch column specific information (column name and the data type thereof)
--from information_schema.columns pseudo entity and loop through for building the INSERT and VALUES clauses
--of an INSERT DML statement. DECLARE @string NVARCHAR(MAX) --for storing the first half of INSERT statement
DECLARE @stringData NVARCHAR(MAX) --for storing the data (VALUES) related statement
DECLARE @dataType NVARCHAR(MAX) --data types returned for respective columns
DECLARE @schemaName NVARCHAR(MAX) --schema name returned from sys.schemas
DECLARE @schemaNameCount int--shema count
DECLARE @QueryString NVARCHAR(MAX) -- provide for the whole query, set @QueryString=' ' --如果有多个schema,选择其中一个schema
SELECT @schemaNameCount=COUNT(*)
FROM sys.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.name = @tableName WHILE(@schemaNameCount>0)
BEGIN --如果有多个schema,依次指定
select @schemaName = name
from
(
SELECT ROW_NUMBER() over(order by s.schema_id) RowID,s.name
FROM sys.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.name = @tableName
) as v
where RowID=@schemaNameCount --Declare a cursor to retrieve column specific information
--for the specified table
DECLARE cursCol CURSOR FAST_FORWARD
FOR
SELECT column_name ,
data_type
FROM information_schema.columns
WHERE table_name = @tableName
AND table_schema = @schemaName OPEN cursCol
SET @string = 'INSERT INTO [' + @schemaName + '].[' + @tableName + ']('
SET @stringData = '' DECLARE @colName NVARCHAR(500) FETCH NEXT FROM cursCol INTO @colName, @dataType PRINT @schemaName
PRINT @colName
IF @@fetch_status <> 0
BEGIN
PRINT 'Table ' + @tableName + ' not found, processing skipped.'
CLOSE curscol
DEALLOCATE curscol
RETURN
END WHILE @@FETCH_STATUS = 0
BEGIN
IF @dataType IN ( 'varchar', 'char', 'nchar', 'nvarchar' )
BEGIN
SET @stringData = @stringData + '''''''''+
isnull(' + @colName + ','''')+'''''',''+'
END
ELSE
IF @dataType IN ( 'text', 'ntext' ) --if the datatype
--is text or something else
BEGIN
SET @stringData = @stringData + '''''''''+
isnull(cast(' + @colName + ' as nvarchar(max)),'''')+'''''',''+'
END
ELSE
IF @dataType = 'money' --because money doesn't get converted
--from varchar implicitly
BEGIN
SET @stringData = @stringData
+ '''convert(money,''''''+
isnull(cast(' + @colName
+ ' as nvarchar(max)),''0.0000'')+''''''),''+'
END
ELSE
IF @dataType = 'datetime'
BEGIN
SET @stringData = @stringData
+ '''convert(datetime,''''''+
isnull(cast(' + @colName + ' as nvarchar(max)),'''')+''''''),''+'
END
ELSE
IF @dataType = 'image'
BEGIN
SET @stringData = @stringData + '''''''''+
isnull(cast(convert(varbinary,' + @colName + ')
as varchar(6)),'''')+'''''',''+'
END
ELSE --presuming the data type is int,bit,numeric,decimal
BEGIN
SET @stringData = @stringData + '''''''''+
isnull(cast(' + @colName + ' as nvarchar(max)),'''')+'''''',''+'
END SET @string = @string + '[' + @colName + ']' + ',' FETCH NEXT FROM cursCol INTO @colName, @dataType
END
--After both of the clauses are built, the VALUES clause contains a trailing comma which needs to be replaced with a single quote. The prefixed clause will only face removal of the trailing comma. DECLARE @Query NVARCHAR(MAX) -- provide for the whole query,
-- you may increase the size
PRINT @whereClause
IF ( @whereClause IS NOT NULL
AND @whereClause <> ''
)
BEGIN
SET @query = 'SELECT ''' + SUBSTRING(@string, 0, LEN(@string))
+ ') VALUES(''+ ' + SUBSTRING(@stringData, 0,
LEN(@stringData) - 2)
+ '''+'')''
FROM ' +@schemaName+'.'+ @tableName + ' WHERE ' + @whereClause
PRINT @query
-- EXEC sp_executesql @query --load and run the built query
--Eventually, close and de-allocate the cursor created for columns information.
END
ELSE
BEGIN
SET @query = 'SELECT ''' + SUBSTRING(@string, 0, LEN(@string))
+ ') VALUES(''+ ' + SUBSTRING(@stringData, 0,
LEN(@stringData) - 2)
+ '''+'')''
FROM ' + @schemaName+'.'+ @tableName END CLOSE cursCol
DEALLOCATE cursCol SET @schemaNameCount=@schemaNameCount-1
IF(@schemaNameCount=0)
BEGIN
SET @QueryString=@QueryString+@query
END
ELSE
BEGIN
SET @QueryString=@QueryString+@query+' UNION ALL '
END
PRINT convert(varchar(max),@schemaNameCount)+'---'+@QueryString
END
EXEC sp_executesql @QueryString --load and run the built query
--Eventually, close and de-allocate the cursor created for columns information.

1、测试脚本如下:

INSERT INTO test1.[customer]([city],[region]) VALUES('','')

InsertGenerator 'customer', null

效果如下:

2、增加筛选条件

InsertGenerator 'customer', 'city=1'

其它内容可以参照桦仔兄的原文章地址。

将表里的数据批量生成INSERT语句的存储过程 继续增强版的更多相关文章

  1. 将表里的数据批量生成INSERT语句的存储过程 增强版

    将表里的数据批量生成INSERT语句的存储过程 增强版 有时候,我们需要将某个表里的数据全部或者根据查询条件导出来,迁移到另一个相同结构的库中 目前SQL Server里面是没有相关的工具根据查询条件 ...

  2. 将表里的数据批量生成INSERT语句的存储过程

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

  3. 自由导入你的增量数据-根据条件将sqlserver表批量生成INSERT语句的存储过程实施笔记

    文章标题: 自由导入你的增量数据-根据条件将sqlserver表批量生成INSERT语句的存储过程增强版 关键字 : mssql-scripter,SQL Server 文章分类: 技术分享 创建时间 ...

  4. 转载-用excel批量生成insert语句

    用excel批量生成insert语句   版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/h ...

  5. 用excel批量生成insert语句

    excel表格中有A.B.C三列数据,分别对应TableName的UserId.UserName.UserPwd三个字段.如下图所示 在excel的D2的位置,也就是A.B.C列的后面一列,添加下面公 ...

  6. 生成Insert语句的存储过程

    ) drop procedure [dbo].[spGenInsertSQL] GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO )) as b ...

  7. 使用java生成备份sqlserver数据表的insert语句

    针对sqlserver数据表的备份工具很多,有时候条件限制需要我们自己生成insert语句,以便后期直接执行这些插入语句.下面提供了一个简单的思路,针对mysql或oracle有兴趣的以后可以试着修改 ...

  8. 使用excel中的数据快速生成sql语句

    在小公司的话,总是会有要开发去导入历史数据(数据从旧系统迁移到新系统上)的时候.这个时候,现场实施或客户会给你一份EXCEL文档,里面包含了一些别的系统上的历史数据,然后就让你导入到现在的系统上面去. ...

  9. 批量生成sql语句,难得

    在工作我们常常要批量生成sql文件,因为业务部门经常给我们的是excel文件,根据我的经验,推荐两种批量生成sql文件方式 1.excel批量生成sql ,sql语句如下 INSERT INTO Ta ...

随机推荐

  1. MySQL Error Handling in Stored Procedures

    http://www.mysqltutorial.org/mysql-error-handling-in-stored-procedures/ mysql存储过程中的异常处理   定义异常捕获类型及处 ...

  2. luogg_java学习_04_数组

    本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! 数组 数组是多个相同类型数据的组合 //1.定义数组 ...

  3. javaweb项目springmvc,和tomcat对静态文件的处理

    1.激活Tomcat的defaultServlet来处理静态文件,web.xml配置 <servlet-mapping> <servlet-name>default</s ...

  4. [moka同学笔记]window下.htacess文件 与linux下.htacess文件

    windows下 # Turn on URL rewritingRewriteEngine On# Installation directoryRewriteBase /# Protect hidde ...

  5. 解决WindowsServer 2008 R2 未注册版一个小时自动强制关机

    仅用来学习交流,请大家购买正版,尊重正版版权. 安装了win2008R2,试了很多激活方法,终于激活后,不知道什么原因,过了一段时间后,每隔一段时间就自动关机,查了一下,发现是 wlms.exe在作祟 ...

  6. Android 手机卫士5--手机防盗

    1,界面介绍 跳转到导航界面的第1个,描述功能 跳转到导航界面的第2个,必须,绑定sim卡,才可以跳转到第三个界面跳转到导航界面的第3个,必须输入电话号码,(两种途径(1,输入2,选择))跳转到导航界 ...

  7. C#如何实现一个简单的流程图设计器

    以前看过不少Window Form开发的流程图设计器,支持节点拖放,非常方便即可设计出很美观的流程图,作为一个程序员,对其内部实现原理一直很好奇,感叹有朝一日自己如果可以开发一款类似的软件那是多么让人 ...

  8. ECharts – 大数据时代,重新定义数据图表

    ECharts 基于 Canvas 的纯 Javascript 图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表.创新的拖拽重计算.数据视图.值域漫游等特性大大增强了用户体验,赋予了用户对 ...

  9. JavaScript基础17——js的Date对象

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. Web安全之CSRF攻击

    CSRF是什么? CSRF(Cross Site Request Forgery),中文是跨站点请求伪造.CSRF攻击者在用户已经登录目标网站之后,诱使用户访问一个攻击页面,利用目标网站对用户的信任, ...