1.今天下午不小心,在调试数据的时候不小心把数据删了,这些数据是我用老长时间输入的,手贱啊,辛亏家里还有这个数据表的备份。前段时间,我发表了一个把导出的数据转换成insert语句,没想到今天在网上找到了一个牛逼的存储过程,帮了我大忙了,这个存储过程可以把指定的表格中的数据转换成insert sql语句,这段存储过程如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 SET ANSI_NULLS ON 2 GO 3 4 SET QUOTED_IDENTIFIER ON 5 GO 6 7 CREATE PROCEDURE [dbo]. [OutputData] 8 @tablename sysname 9 AS 10 declare @column varchar (1000) 11 declare @columndata varchar (1000) 12 declare @sql varchar (4000) 13 declare @xtype tinyint 14 declare @name sysname 15 declare @objectId int 16 declare @objectname sysname 17 declare @ident int 18 19 Set nocount On 20 Set @objectId=object_id (@tablename) 21 22 if @objectId Is null -- 判斷對象是否存在 23 begin 24 print 'The object not exists' 25 return 26 End 27 Set @objectname=object_name (@objectId) 28 29 if @objectname Is null Or charindex(@objectname ,@tablename)= 0 --此判断不严密 30 begin 31 print 'object not in current database' 32 return 33 End 34 35 if OBJECTPROPERTY(@objectId ,'IsTable') <> 1 -- 判斷對象是否是table 36 begin 37 print 'The object is not table' 38 return 39 End 40 41 Select @ident=status &0x80 from syscolumns where id=@objectid And status&0x80 =0x80 42 43 if @ident Is Not null 44 print 'SET IDENTITY_INSERT ' +@TableName+ ' ON' 45 46 declare syscolumns_cursor cursor 47 for Select c .name, c.xtype from syscolumns c 48 where c.id =@objectid 49 order by c .colid 50 open syscolumns_cursor 51 Set @column='' 52 Set @columndata='' 53 fetch Next from syscolumns_cursor into @name ,@xtype 54 while @@fetch_status <>- 1 55 begin 56 if @@fetch_status<>-2 57 begin 58 if @xtype Not in(189 ,34, 35,99 ,98) --timestamp不需处理, image,text,ntext,sql_variant 暂时不处理 59 begin 60 Set @column=@column +Case when len (@column)= 0 Then'' else ','end+ @name 61 Set @columndata=@columndata +Case when len (@columndata)= 0 Then '' else ','','','end 62 +Case when @xtype in( 167,175 ) Then '''''''''+'+@name +'+''''''''' --varchar,char 63 when @xtype in( 231,239 ) Then '''N''''''+'+ @name+'+''''''''' --nvarchar,nchar 64 when @xtype=61 Then '''''''''+convert(char(23),' +@name+ ',121)+''''''''' --datetime 65 when @xtype=58 Then '''''''''+convert(char(16),' +@name+ ',120)+''''''''' --smalldatetime 66 when @xtype=36 Then '''''''''+convert(char(36),' +@name+ ')+''''''''' --uniqueidentifier 67 else @name End 68 End 69 End 70 fetch Next from syscolumns_cursor into @name ,@xtype 71 End 72 close syscolumns_cursor 73 deallocate syscolumns_cursor 74 75 Set @sql='set nocount on select ''insert '+@tablename+ '('+@column +') values(''as ''--'','+@columndata +','')'' from '+@tablename 76 77 print '--'+@sql 78 exec( @sql) 79 80 if @ident Is Not null 81 print 'SET IDENTITY_INSERT ' +@TableName+ ' OFF' 82 83 GO
2.希望能对各位有用。