Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >sql server根据表中数据生成insert语句

sql server根据表中数据生成insert语句

作者头像
跟着阿笨一起玩NET
发布于 2018-09-18 08:07:58
发布于 2018-09-18 08:07:58
1.8K00
代码可运行
举报
运行总次数:0
代码可运行

几个收藏的根据数据库生成Insert语句的存储过程[修正版]

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
-- ======================================================
--根据表中数据生成insert语句的存储过程
--建立存储过程,执行spGenInsertSQL 表名
--感谢playyuer
----感谢szyicol
-- ======================================================
CREATE   proc [dbo].[spGenInsertSQL] 
(@tablename varchar(256))
as
begin
  declare @sql varchar(8000)
  declare @sqlValues varchar(8000)
 
  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

-- ======================================================
--根据表中数据生成insert语句的存储过程
--建立存储过程,执行proc_insert 表名
--感谢Sky_blue
--感谢szyicol
-- ======================================================
CREATE proc [dbo].[proc_insert] (@tablename varchar(256))
as
begin
       set nocount on
       --declare @tablename varchar(256)
       --set @tablename = 'AD'
       declare @sqlstr varchar(4000)
       declare @sqlstr1 varchar(4000)
       declare @sqlstr2 varchar(4000)
       select @sqlstr='select ''insert '+@tablename
 
       select @sqlstr1=''
       select @sqlstr2=' ('
       select @sqlstr1= ' values ( ''+'
       select @sqlstr1=@sqlstr1+col+'+'',''+' ,@sqlstr2=@sqlstr2+ '[' + name + ']' +',' from (select case 
--     when a.xtype =173 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.length*2+2)+'),'+a.name +')'+' end'
       when a.xtype =104 then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(1),['+a.name +'])'+' end'
       when a.xtype =175 then 'case when ['+a.name+'] is null then ''NULL'' else '+'''''''''+'+'replace(['+a.name+'],'''''''','''''''''''')' + '+'''''''''+' end'
       when a.xtype =61  then 'case when ['+a.name+'] is null then ''NULL'' else '+'''''''''+'+'convert(varchar(23),['+a.name +'],121)'+ '+'''''''''+' end'
       when a.xtype =106 then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.xprec+2)+'),['+a.name +'])'+' end'
       when a.xtype =62  then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(23),['+a.name +'],2)'+' end'
       when a.xtype =56  then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(11),['+a.name +'])'+' end'
       when a.xtype =60  then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(22),['+a.name +'])'+' end'
       when a.xtype =239 then 'case when ['+a.name+'] is null then ''NULL'' else '+'''''''''+'+'replace(['+a.name+'],'''''''','''''''''''')' + '+'''''''''+' end'
       when a.xtype =108 then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.xprec+2)+'),['+a.name +'])'+' end'
       when a.xtype =231 then 'case when ['+a.name+'] is null then ''NULL'' else '+'''''''''+'+'replace(['+a.name+'],'''''''','''''''''''')' + '+'''''''''+' end'
       when a.xtype =59  then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(23),['+a.name +'],2)'+' end'
       when a.xtype =58  then 'case when ['+a.name+'] is null then ''NULL'' else '+'''''''''+'+'convert(varchar(23),['+a.name +'],121)'+ '+'''''''''+' end'
       when a.xtype =52  then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(12),['+a.name +'])'+' end'
       when a.xtype =122 then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(22),['+a.name +'])'+' end'
       when a.xtype =48  then 'case when ['+a.name+'] is null then ''NULL'' else '+'convert(varchar(6),['+a.name +'])'+' end'
--     when a.xtype =165 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.length*2+2)+'),'+a.name +')'+' end'
       when a.xtype =167 then 'case when ['+a.name+'] is null then ''NULL'' else '+'''''''''+'+'replace(['+a.name+'],'''''''','''''''''''')' + '+'''''''''+' end'
       else '''NULL'''
       end as col,a.colid,a.name
       from syscolumns a where a.id = object_id(@tablename) and a.xtype <>189 and a.xtype <>34 and a.xtype <>35 and  a.xtype <>36
       )t order by colid
       select @sqlstr=@sqlstr+left(@sqlstr2,len(@sqlstr2)-1)+') '+left(@sqlstr1,len(@sqlstr1)-3)+')'' from '+@tablename
       --print @sqlstr
       exec( @sqlstr)
       set nocount off
end

原文:几个收藏的根据数据库生成Insert语句的存储过程

修正了表中的字段如果是SQL中的关键字(如Order)时,生成的脚本执行会出错的bug

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013-04-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
SQL Server 存储过程生成insert语句
你肯定有过这样的烦恼,同样的表,不同的数据库,加入你不能执行select  insert 那么你肯定需要一条这样的存储过程,之需要传入表明,就会给你生成数据的插入语句。 当然数据表数量太大,你将最好用别的方式 Create proc [dbo].[spGenInsertSQL] (@tablename varchar(256)) as begin declare @sql varchar(8000) declare @sqlValues varchar(8000) set @sql =' (' set
用户1149182
2018/01/16
2K0
用Sql生成数据插入Sql脚本
CREATE PROCEDURE dbo.UspOutputData @tablename sysname AS declare @column varchar(1000) declare @columndata varchar(1000) declare @sql varchar(4000) declare @xtype tinyint declare @name sysname declare @objectId int declare @objectname sysname decl
脑洞的蜂蜜
2018/02/01
1.4K0
t-sql导出EXCEL语句
/*=================== 导入/导出 Excel 的基本方法 ===================*/
jack.yang
2025/04/05
790
powerdesigner 15 如何导出sql schema
PowerDesigner导出所有SQL脚本 操作:Database=>Generate Database PowerDesigner怎么导出建表sql脚本 1 按照数据库类型,切换数据库。 Database-> Change Current DBMS... 2 生成sql脚本 Database -> Database Generation 的Preview选项卡 点击保存按钮,保存产生的sql脚本到本地。 【注意】: 1 本人使用的powerDesigner是15.2版本。 2 产生出的sql脚本一般会有
Java学习123
2018/05/16
1.8K0
SQL SERVER将查询数据转为INSERT语句
1、在Sql Server数据库中创建存储过程 个人感觉挺有用,Mark一下。 CREATE PROC sp_Data2InsertSQL @TableName AS VARCHAR(100) AS DECLARE xCursor CURSOR FOR SELECT name,xusertype FROM syscolumns WHERE (id = OBJECT_ID(@TableName)) DECLARE @F1 VARCHAR(100) DECLARE @F2 integer DECLA
BrianLee
2022/05/30
2.1K0
SQL SERVER将查询数据转为INSERT语句
Sql Server数据导出EXCEL
  ,@path='c:\',@fname='aa.xls',@sheetname='地区资料'
jack.yang
2025/04/05
1160
给SQL补充一个查看表结构的存储过程
数据库中表太多,要查看某个表的结构比较费劲,用此存储过程比较方便;   CRM /******************************************** * 根据表名得到表信息,包括字段说明      ********************************************/    CREATE PROC [dbo].[sp_help_table] (@tableName VARCHAR(200), @ColumnLike VARCHAR(200) = NULL)     
跟着阿笨一起玩NET
2018/09/18
5490
国产化之路 Linux Mono下的asp.net 开发笔记(二)
       由于原来使用的是MS SQL SERVER 数据库,想实现在SQL查询分析器里,生成创建达梦数据表的脚本。因此写了一个存储过程,该过程实现输入一个表名,会自动转换为对应的脚本,包括创建表和创建键值(修改表)的脚本输出。这是一个适合自己框架的范例程序,大家有兴趣可以进一步修改。脚本代码如下:
初九之潜龙勿用
2024/06/20
1620
C#结合html2canvas生成切割图片并导出到PDF
html2canvas 是一个 JavaScript 库,它可以把任意一个网页中的元素(包括整个网页)绘制到指定的 canvas 中,适用于生成网截图或将指定元素容器内容保存为图像等。现有需求如下:
初九之潜龙勿用
2025/02/06
2250
C#结合html2canvas生成切割图片并导出到PDF
[翻译]如何从 SQL Server 恢复已删除的数据
在我使用 SQL Server 的这些年里,最常见的问题之一一直是“我们如何恢复已删除的记录?”
保持热爱奔赴山海
2024/05/10
7170
Sql Server 中 根据具体的值 查找该值所在的表和字段
在我们的工作中经常遇到这样一个问题,在页面中保存一条数据,有个字段值为“张三”,但是,不知道这条数据保存在了哪个表中,现在我们想要追踪该值是存储到了那个表的那个字段中,具体要怎么操作呢?下面我们可以借助存储过程来解决这一问题
jamesjiang
2022/11/20
8.1K0
Sql Server 中 根据具体的值 查找该值所在的表和字段
记录容易忘记的方法
提取每个分类前n条记录 SELECT ID, Name, CategoryID FROM TableName AS a WHERE (ID IN (SELECT TOP (n) ID FROM TableName AS b WHERE (a.CategoryID = CategoryID))) 0、更改数据库的路径 USE master Go ALTER DATABASE tempdb MODIFY FILE (NAME = tempdev, FILE
用户1174620
2018/02/26
6370
记录容易忘记的方法
解密encrypt的存储过程
--破解函数,过程,触发器,视图.仅限于SQLSERVER2000 IF EXISTS (select 1 from dbo.sysobjects where id = object_id(N'[dbo].[SP_DECRYPT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SP_DECRYPT] GO CREATE PROCEDURE sp_decrypt(@objectname varchar(50)) AS begin set nocount on --破解字节不受限制,适用于SQLSERVER2000存储过程,函数,视图,触发器 --修正上一版视图触发器不能正确解密错误 begin tran declare @objectname1 varchar(100),@orgvarbin varbinary(8000) declare @sql1 nvarchar(4000),@sql2 varchar(8000),@sql3 nvarchar(4000),@sql4 nvarchar(4000) DECLARE @OrigSpText1 nvarchar(4000), @OrigSpText2 nvarchar(4000) , @OrigSpText3 nvarchar(4000), @resultsp nvarchar(4000) declare @i int,@status int,@type varchar(10),@parentid int declare @colid int,@n int,@q int,@j int,@k int,@encrypted int,@number int select @type=xtype,@parentid=parent_obj from sysobjects where id=object_id(@objectname) create table #temp(number int,colid int,ctext varbinary(8000),encrypted int,status int) insert #temp SELECT number,colid,ctext,encrypted,status FROM syscomments WHERE id = object_id(@objectname) select @number=max(number) from #temp set @k=0 while @k<=@number begin if exists(select 1 from syscomments where id=object_id(@objectname) and number=@k) begin if @type='P' set @sql1=(case when @number>1 then 'ALTER PROCEDURE '+ @objectname +';'+rtrim(@k)+' WITH ENCRYPTION AS ' else 'ALTER PROCEDURE '+ @objectname+' WITH ENCRYPTION AS ' end) if @type='TR' begin declare @parent_obj varchar(255),@tr_parent_xtype varchar(10) select @parent_obj=parent_obj from sysobjects where id=object_id(@objectname) select @tr_parent_xtype=xtype from sysobjects where id=@parent_obj if @tr_parent_xtype='V' begin set @sql1='ALTER TRIGGER '+@objectname+' ON '+OBJECT_NAME(@parentid)+' WITH ENCRYPTION INSTERD OF INSERT AS PRINT 1 ' end else begin set @sql1='ALTER TRIGGER '+@objectname+' ON '+OBJECT_NAME(@parentid)+' WITH ENCRYPTION FOR INSERT AS PRINT 1 ' end end if @type='FN' or @type='TF' or @type='IF' set @sql1=(case
jack.yang
2025/04/05
450
数据字典生成工具之旅(8):SQL查询表的约束默认值等信息
本文主要介绍了数据字典生成工具在.NET平台下的实现,通过实例讲解了如何使用该工具对数据库进行查询,并生成数据字典。同时还介绍了在工具中如何自定义输出内容,以及如何使用该工具对数据库表进行批量操作。
用户1168362
2018/01/05
1.1K0
数据字典生成工具之旅(8):SQL查询表的约束默认值等信息
数据库干货:整理SQLServer非常实用的脚本
今天给大家分享自己在工作当中用到的SQLServer一些常用的脚本,希望能对大家有所帮助!
小明互联网技术分享社区
2021/02/25
3860
数据库干货:整理SQLServer非常实用的脚本
SQL之经典SQL语句大全
经典SQL语句大全 一、基础 1、说明:创建数据库 CREATE DATABASE database-name  2、说明:删除数据库 drop database dbname 3、说明:备份sql server --- 创建 备份数据的 device USE master EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' --- 开始 备份 BACKUP DATABASE pubs TO testBack  4
互联网金融打杂
2018/04/03
1.4K0
SQL语句大全中的sql语句备忘录—sql日常使用指北
CRUD:增查改删,即,create/read/update/delate 主要被用在描述软件系统中数据库或者持久层的基本操作功能
周陆军博客
2023/05/19
1.1K0
mysql sql语句大全
根据已有的表创建新表: A:create table tabnew like tabold (使用旧表创建新表) B:create table tabnew as select col1,col2… from tabold definition only 5、说明:删除新表
Ai学习的老章
2019/04/10
12.4K1
SQL Server 常用近百条SQL语句(收藏版)
sp_configure显示或更改当前服务器的全局配置设置。 RECONFIGURE表示SQL Server不用重新启动就立即生效 。
数据和云
2020/04/02
2.7K0
如何根据日志查看删除的数据(转译)
原文地址:https://raresql.com/2011/10/22/how-to-recover-deleted-data-from-sql-sever/   在我的SQLServer的工作中,最经常被问到的一个问题就是“能恢复删除的数据吗?”   我的回答是肯定的,注意下面的数据类型是可以通过脚本直接恢复的,当然数据库的版本要在SQLServer2005 以上才行。 经过讨论发现2008和2012以及2014的express版本也不能实现脚本直接恢复。 image text uniqueidentif
用户1217611
2018/01/30
7.6K0
推荐阅读
相关推荐
SQL Server 存储过程生成insert语句
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验