Stored Procedures | scripts | data
Author: zlt982001
Stored procedures that generate SQL scripts for table data:
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
DECLARE @ident int
SET NOCOUNT ON
Set @objectId =object_id (@tablename)
If @objectId is null--whether an image exists
Begin
Print ' Object Not EXISTS '
Return
End
Set @objectname =rtrim (object_name (@objectId))
If @objectname is null or CHARINDEX (@objectname, @tablename) =0-This is not strictly judged
Begin
Print ' object not in the current database '
Return
End
If OBJECTPROPERTY (@objectId, ' istable ') < > 1--whether the judgment is a table
Begin
print ' The object is not table '
Return
End
Select @ident =status&0x80 from syscolumns where id= @objectid and status&0x80=0x80
If @ident is not null
print ' SET identity_insert ' + @TableName + ' on '
DECLARE syscolumns_cursor cursor
For a select C.name,c.xtype from syscolumns C where c.id= @objectid ORDER by C.colid
Open Syscolumns_cursor
Set @column = '
Set @columndata = '
FETCH NEXT from Syscolumns_cursor into @name, @xtype
While @ @fetch_status < >-1
Begin
If @ @fetch_status < >-2
Begin
If @xtype not in (189,34,35,99,98)--timestamp does not need to be processed, image,text,ntext,sql_variant temporarily does not handle
Begin
Set @column = @column +case when Len (@column) =0 then ' Else ', ' end+ @name
Set @columndata = @columndata +case when Len (@columndata) =0 then ' Else ', ', ', ', '
End
+case when @xtype in (167,175) then ' ' + ' + @name + ' + ' "'" '--varchar,char
When @xtype in (231,239) then ' ' N ' ' ' ' + ' + ' + ' + ' + ' + ' + ' + ' + ' + ' + ' + ' + ' + ' "'--nvarchar,nchar
When @xtype =61 then ' "' +convert (char), ' + @name + ', 121) + '" ""--datetime
When @xtype =58 then ' "' +convert (char), ' + @name + '," + "" "" "--smalldatetime
When @xtype =36 then ' "" ' +convert (char), ' + @name + ') + ' "'--uniqueidentifier
else @name End
End
End
FETCH NEXT from Syscolumns_cursor into @name, @xtype
End
Close Syscolumns_cursor
Deallocate syscolumns_cursor
Set @sql = ' Set NOCOUNT on select ' Insert ' + @tablename + ' (' + @column + ') VALUES (' as '---', ' + @columndata + ', ') ' From ' + @tablename
Print '--' + @sql
EXEC (@sql)
If @ident is not null
print ' SET identity_insert ' + @TableName + ' off '
Go
EXEC uspoutputdata your table name