1、创建存储过程

CREATE PROC [dbo].[sp_get_InsertSql]

    @dbName              VARCHAR ( )= '' ,    -- 数据库名称

    @tabList          VARCHAR ( max ), -- 要导出数据的表名,表名之间用逗号隔开,过滤条件跟在表名后面,用空格隔开如 tab1 where col1!=, tab2, tab3  

    @IncludeIdentity  BIT = ,         -- 是否包含自增字段

    @DeleteOldData       BIT =          -- 插入前删除所有数据

AS

    DECLARE

       @index     INT ,

       @wi        INT ,

       @SQL       VARCHAR ( max ),

       @SQL1      VARCHAR ( max ),

       @tabName   VARCHAR ( ),

       @colName   VARCHAR ( ),

       @colType   VARCHAR ( ),

       @tabPrefix VARCHAR ( ),

       @cols      VARCHAR ( max ),

       @colsData  VARCHAR ( max ),

       @SQLWhere  VARCHAR ( ),       

       @SQLIdentityOn    VARCHAR ( MAX ),

       @SQLIdentityOff VARCHAR ( MAX ),

       @SQLDelete    VARCHAR ( max ),

       @SQLIfBegin       VARCHAR ( ),

       @SQLIfEnd     VARCHAR ( ),

       @SQLNull      VARCHAR ( );       

    DECLARE @t_tb TABLE ( TB varchar ( ), Sqlwhere varchar ( ), SN BIGINT IDENTITY ( , ))

    DECLARE @tb TABLE ( insert_sql VARCHAR ( max ), SN BIGINT IDENTITY ( , ));

    DECLARE @colList TABLE ( colName VARCHAR ( ), colType VARCHAR ( ),

       colValueL VARCHAR ( ), colValueR VARCHAR ( ), selColName VARCHAR ( ));

BEGIN

    SET NOCOUNT ON

    SET @tabList = REPLACE ( @tabList, CHAR ( ), '' )

    SET @tabList = REPLACE ( @tabList, CHAR ( ), '' )

    SET @tabList = REPLACE ( @tabList, CHAR ( ), '' )

    SET @dbName = LTRIM ( RTRIM ( @dbName))

    SET @index = CHARINDEX ( ',' , @tabList)

    IF LEN ( @dbName) > 

       SET @tabPrefix = @dbName + '..'

    ELSE

       SET @tabPrefix = '' ;

    WHILE @index >  AND @index IS NOT NULL

    BEGIN

       SET @tabName = SUBSTRING ( @tabList, , @index- )

       SET @wi= CHARINDEX ( ' where' , LTRIM ( @tabName))

       IF @wi= 

           SET @wi = LEN ( @tabName)

       INSERT INTO @t_tb( tb, Sqlwhere) VALUES ( SUBSTRING ( @tabName, , @wi), SUBSTRING ( @tabName, @wi+ , LEN ( @tabName)- @wi))

       SET @tabList = SUBSTRING ( @tabList, @index+ , LEN ( @tabList)- @index)

       SET @index = CHARINDEX ( ',' , @tabList)

    END

    IF @index =  OR @index IS NULL

       SET @tabName = @tabList

    ELSE

       SET @tabName = SUBSTRING ( @tabList, , @index)

    SET @wi= CHARINDEX ( ' where' , LTRIM ( @tabName))

    IF @wi= 

       SET @wi = LEN ( @tabName)

    INSERT INTO @t_tb( tb, Sqlwhere) VALUES ( SUBSTRING ( @tabName, , @wi), SUBSTRING ( @tabName, @wi+ , LEN ( @tabName)- @wi))

    SELECT @SQL1 = 'select INSERT_SQL='';SET NOCOUNT ON' + CHAR ( ) + '''' +

                  ' union all '

    SELECT @SQLNull = 'select INSERT_SQL=''  '' union all ' ,     

          @SQLIfBegin = 'select INSERT_SQL=''    If @Error=0 begin ''' +

                  ' union all ' ,

          @SQLIfEnd = ' union all ' + 'select INSERT_SQL=''    end;'''

    DECLARE tab_cur CURSOR FOR

    SELECT t. name , tb. Sqlwhere FROM sys.tables t

    INNER JOIN @t_tb tb ON t. name = RTRIM ( LTRIM ( tb. TB))

    ORDER BY tb. SN   

    OPEN tab_cur

    FETCH NEXT FROM tab_cur INTO @tabName, @SQLWhere

    WHILE @@FETCH_STATUS =  BEGIN

       DELETE FROM @colList

       IF NOT EXISTS( SELECT  FROM sys.objects WHERE name = @tabName AND type = 'U' ) BEGIN

           PRINT ( @tabName + N' 不存在! ' )

           RAISERROR ( @tabName, , - );

           FETCH NEXT FROM tab_cur INTO @tabName, @SQLWhere

           CONTINUE ;

       END

       INSERT INTO @colList( colName, colType, colValueL, colValueR)

       SELECT c. NAME , t. name , '' , ''

       FROM sys.columns c

       INNER JOIN sys.tables tab

           ON c. object_id = tab. object_id

       INNER JOIN sys.types t

           ON c. user_type_id = t. user_type_id

       WHERE c. is_computed= 

           AND tab. name = @tabName

       IF @IncludeIdentity= 

           DELETE FROM @colList WHERE colName IN(

              SELECT name FROM sys.columns WHERE object_id = OBJECT_ID ( @tabName) AND is_identity= )

       UPDATE @colList SET colValueL= 'RTRIM(' , colValueR = ')'

       WHERE colType IN( 'text' , 'varchar' , 'nvarchar' , 'char' , 'uniqueidentifier' , 'datetime' , 'nchar' , 'sysname' )

       SELECT @cols= '' , @colsData = '' , @SQL = '' ;

       UPDATE @colList SET colName = '[' + colName + ']'    

       UPDATE @colList SET selColName= colName   

       UPDATE @colList SET colValueL= 'replace(' + colValueL, colValueR = colValueR+ ','''''''','''''''''''')'

       WHERE colType IN( 'text' , 'varchar' , 'nvarchar' , 'char' , 'nchar' , 'sysname' )  

       UPDATE @colList SET colValueL=

           CASE WHEN colType IN( 'text' , 'varchar' , 'nvarchar' , 'char' , 'uniqueidentifier' , 'datetime' , 'nchar' , 'sysname' ) THEN '''''''''+' ELSE '' END

              + colValueL,

           colValueR = colValueR + CASE WHEN colType IN( 'text' , 'varchar' , 'nvarchar' , 'char' , 'nchar' , 'datetime' , 'uniqueidentifier' , 'sysname' ) THEN '+''''''''' ELSE '' END

       SELECT @cols = @cols + colName + ', ' ,

           @colsData = @colsData + 'isnull(' +

              colValueL +          

              CASE WHEN colType= 'datetime' THEN 'convert(varchar(20),' + colName+ ',120)'

              WHEN colType= 'uniqueidentifier' THEN 'convert(varchar(50),' + colName+ ')'

              WHEN colType= 'text' THEN 'convert(nvarchar(max),' + colName+ ')'

              WHEN colType= 'sysname' THEN 'convert(nvarchar(max),' + colName+ ')'

              WHEN colType= 'varbinary' OR colType= 'BINARY' OR colType= 'image'

                  THEN 'master.dbo.fn_varbintohexsubstring(1,' + colName+ ',1,0)'              

              ELSE   'cast(' + colName+ ' as nvarchar(max))' END

              + colValueR + ',''null'')+'', ''+'

       FROM @colList

       SELECT @cols = LEFT( @cols, LEN ( @cols)- ),

              @colsData = LEFT( @colsData, LEN ( @colsData)- ),

              @SQL = 'select INSERT_SQL=''print ''''Table Name:  ' + CHAR ( )+ @tabName + '''''''' +

                  ' union all '

       SELECT @cols = 'select INSERT_SQL=''INSERT INTO ' + @tabPrefix + @tabName + '(' + @cols+ ')' ,

           @colsData = '  VALUES(''+' + @colsData + '+'');'' FROM ' + @tabPrefix + @tabName

       SELECT @colsData = @colsData + ' ' + ISNULL ( @SQLWhere, '' )

       IF @DeleteOldData=  

           SET @SQLDelete = 'select INSERT_SQL='''' +

                  ''Delete from ' + @tabPrefix + @tabName + '; ''' +

                  ' union all '

       ELSE

           SET @SQLDelete= ''

       IF @IncludeIdentity=  AND EXISTS( SELECT  FROM sys.columns WHERE object_id = OBJECT_ID ( @tabName) AND is_identity= )

       BEGIN

           SELECT @SQLIdentityOn = 'select INSERT_SQL=''SET IDENTITY_INSERT ' + @tabPrefix + @tabName + ' ON;''' +

                  ' union all ' ,

              @SQLIdentityOff = ' union all ' + 'select INSERT_SQL=''SET IDENTITY_INSERT ' + @tabPrefix + @tabName + ' OFF;'''

       END

       ELSE

       BEGIN

           SELECT @SQLIdentityOff = '' ,

              @SQLIdentityOn = '' ;

       END

       INSERT INTO @tb( insert_sql)

       EXECUTE ( @SQLNull + @SQLIfBegin + @SQL+ @SQLDelete+ @SQLIdentityOn + @cols+ @colsData + @SQLIdentityOff + @SQLIfEnd)

       FETCH NEXT FROM tab_cur INTO @tabName, @SQLWhere

    END

    CLOSE tab_cur

    DEALLOCATE tab_cur

    SELECT insert_sql FROM @tb ORDER BY sn

END 

2、执行存储过程

EXECUTE  [dv_etc].[dbo].[sp_get_InsertSql]
@dbName='dv_etc' --数据库名称
,@tabList='etc_city' --表名称
,@IncludeIdentity=
,@DeleteOldData=

利用存储过程将表中的数据生成Insert语句的更多相关文章

  1. 利用sql 存储过程把表中内容自动生成insert语句

    选中所在数据库 执行创建存储过程的sql CREATE proc [dbo].[spGenInsertSQL] (@tablename nvarchar(256),@sqlwhere varchar( ...

  2. 将excle表中得数据生成insert语句插入到数据库中

    第一步:输入公式 第二步:拽住右下角得+往下拖拽

  3. 如何将sqlserver表中的数据导出sql语句或生成insert into语句 [转]

    输入表名,生成插入语句 drop proc proc_insert //如果存在就删除 go create proc proc_insert (@tablename varchar(256)) as ...

  4. 表中相同数据的sql语句

    1.查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断select * from peoplewhere peopleId in (select   peopleId from  ...

  5. oracle----修改表中的数据

    1. 修改表中的数据:UPDATE语句: 语法: UPDTAE table_name SET column1 = value1,... [WHERE conditions] (2),无条件的更新(没有 ...

  6. (笔记)Mysql命令insert into:向表中插入数据(记录)

    insert into命令用于向表中插入数据. insert into命令格式:insert into <表名> [(<字段名1>[,..<字段名n > ])] v ...

  7. Mysql命令insert into:向表中插入数据(记录)

    insert into命令用于向表中插入数据. insert into命令格式:insert into <表名> [(<字段名1>[,..<字段名n > ])] v ...

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

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

  9. 【MYSQL 清空所有的的表中的数据的SQL的生成】

    MYSQL 清空所有的的表中的数据的SQL的生成 select Concat('TRUNCATE TABLE ', TABLE_NAME, ';') from INFORMATION_SCHEMA.T ...

随机推荐

  1. ORA-14452: 试图创建, 更改或删除正在使用的临时表中的索引

    ORA-14452: 试图创建, 更改或删除正在使用的临时表中的索引       因为表KOL_XX_FIN050_TEMP 为临时表,而且有其他session正在使用. 处理步骤: 1.先从 dba ...

  2. Java中Scanner类

    java.util.Scanner类,这是一个用于扫描输入文本的新的实用程序

  3. 1671. Anansi's Cobweb(并查集)

    1671 并查集 对于询问删除边之后的连通块 可以倒着加边 最后再倒序输出 #include <iostream> #include<cstdio> #include<c ...

  4. 第二部分 overlay 架构初探

    1 overlay可能支持的颜色格式/* possible overlay formats可能支持的颜色格式 */enum {    OVERLAY_FORMAT_RGBA_8888    = HAL ...

  5. [C#] 我的log4net使用手册

    1. log4net简介 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介.Java平台下,它还 ...

  6. TRSWCM学习问题总结

    1,置标属性"id"是用来制定调用那个栏目的数据(全字配备,可以文字匹配好奇怪,好不专业.所以建议创建栏目或者站点的时候,将唯一标识设置成英文,这样才符合程序比对习惯) 2,需要添 ...

  7. [swustoj 917] K-lucky-number

    K-lucky-number(0917) 问题描述 K-lucky-number is defined as add up the number of each bit is a multiple o ...

  8. [.NET MVC进阶系列03] Views 视图基础

    [注:此文对应Chapter 3:Views] 一.View的功能: 1.View用来呈现页面UI,通过Controller来指定View: 要注意的是,MVC和以前基于文件的Web应用不同,URL指 ...

  9. Java [Leetcode 258]Add Digits

    题目描述: Given a non-negative integer num, repeatedly add all its digits until the result has only one ...

  10. 再见WCF

    转眼微软的WCF已走过十个年头,它是微软通信框架的集大成者,将之前微软所有的通信框架进行了整合,提供了统一的应用方式.记得从自己最开始做MFC时,就使用过Named Pipe命名管道,之后做Winfo ...