?
通常情况下,SQL Server里面的生成SQL脚本,只会包含数据库及表的字段结构,而不会包含表的数据,也就是SQL脚本里面只有Create database,Create table 这样的语句,没有insert into。
因为SQL Server并不包含这个功能,只能靠第三方的代码了。
以下存储过程可以实现:
?
?
CREATE PROCEDURE dbo.UspOutputData@tablename sysnameASdeclare @column varchar(1000)declare @columndata varchar(1000)declare @sql varchar(4000)declare @xtype tinyintdeclare @name sysnamedeclare @objectId intdeclare @objectname sysnamedeclare @ident intset nocount onset @objectId=object_id(@tablename)if @objectId is null -- 判断对象是否存在beginprint 'The object not exists'returnendset @objectname=rtrim(object_name(@objectId))if @objectname is null or charindex(@objectname,@tablename)=0 --此判断不严密beginprint 'object not in current database'returnendif OBJECTPROPERTY(@objectId,'IsTable') < > 1 -- 判断对象是否是tablebeginprint 'The object is not table'returnendselect @ident=status&0x80 from syscolumns where [email protected] and status&0x80=0x80if @ident is not nullprint 'SET IDENTITY_INSERT [email protected]+' ON'declare syscolumns_cursor cursorfor select c.name,c.xtype from syscolumns c where [email protected] order by c.colidopen syscolumns_cursorset @column=''set @columndata=''fetch next from syscolumns_cursor into @name,@xtypewhile @@fetch_status < >-1beginif @@fetch_status < >-2beginif @xtype not in(189,34,35,99,98) --timestamp不需处理,image,text,ntext,sql_variant 暂时不处理beginset @[email protected]+case when len(@column)=0 then'' else ',[email protected]set @[email protected]+case when len(@columndata)=0 then '' else ','','','end+case when @xtype in(167,175) then [email protected]+'+''''''''' --varchar,charwhen @xtype in(231,239) then [email protected]+'+''''''''' --nvarchar,ncharwhen @xtype=61 then '''''''''+convert(char(23),[email protected]+',121)+''''''''' --datetimewhen @xtype=58 then '''''''''+convert(char(16),[email protected]+',120)+''''''''' --smalldatetimewhen @xtype=36 then '''''''''+convert(char(36),[email protected]+')+''''''''' --uniqueidentifierelse @name endendendfetch next from syscolumns_cursor into @name,@xtypeendclose syscolumns_cursordeallocate syscolumns_cursorset @sql='set nocount on select ''insert [email protected]+'([email protected]+') values(''as ''--'',[email protected]+','')'' from [email protected]print [email protected]exec(@sql)if @ident is not nullprint 'SET IDENTITY_INSERT [email protected]+' OFF'GO??
使用方法:
exec UspOutputData 你的表名
?
选择【执行模式】为“以文本显示结果”,然后将运行后的结果存成.sql,加上用SQL Server生成的数据库脚本就可以了。
另外可以利用第三方工具,导出数据可以用powerbuilder。在database painter里面,用SQL选出,或者直接打开表,点击生成的list datawindow,然后在菜单file->save rows as->选择SQL,那么生成的SQL语句就包括建表和insert数据的SQL了。
?
注意导出的语句,有要加上into关键字。