文章继续 桦仔兄的文章 将表里的数据批量生成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. 关于mybatis 的mapper namespace 作用及解析

    因为语言惯性,大部分的namespace 在语言级别*来说是作为一种限定性标识来用,起到唯一或一类的标识.来看看语言(以PHP语言为例)上的namespace的作用实例 一.namespace 在PH ...

  2. Scalaz(2)- 基础篇:随意多态-typeclass, ad-hoc polymorphism

    scalaz功能基本上由以下三部分组成: 1.新的数据类型,如:Validation, NonEmptyList ... 2.标准scala类型的延伸类型,如:OptionOps, ListOps . ...

  3. Linux练习

    1.创建目录/perm ,在/perm目录下创建文件newfile ,授予/perm目录所有用户都有rwx权限: #创建perm目录 [root@CentOS62 ~]# mkdir perm [ro ...

  4. 【LeetCode】389 Find the Difference(java)

    原题 Given two strings s and t which consist of only lowercase letters. String t is generated by rando ...

  5. Node.JS事件驱动机制

    1.事件驱动程序绑定事件及事件的处理程序 eventEmitter.on('eventName', eventHandler); 我们可以通过程序触发事件 // 触发事件 eventEmitter.e ...

  6. [iOS] 建立与使用Framework

    [iOS] 建立与使用Framework 前言 使用XCode开发iOS项目时,开发人员可以将可重用的程序代码,封装为Library或是Framework来提供其他开发人员使用.这两种封装方式在使用的 ...

  7. Tourist.js – 简单灵活的操作指南和导航插件

    Tourist.js 是一个基于 Backbone 和 jQuery 开发的轻量库,帮助你在应用程序创建简单易用的操作指南和导航功能.相比网站,它更适合用于复杂的,单页网站类型的应用程序.Touris ...

  8. 初识mfc

    今天主要了解了Visual C++的开发环境Visual Studio(话说以前都是用来调试控制台程序的)和用mfc写了一个最简单的程序. 目前微软大力推广的开发环境就是vs,它的集成度相当高,方便程 ...

  9. js 将json对象转成字符串

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  10. mysql服务突然丢失解决方案

    mysql服务突然丢失解决方案 今天系统从win7更新到win10之后,mysql突然没了,使用navicat连接提示如下: 看到这个,以为自己的mysql服务没启动,于是打开服务找mysql服务,发 ...