测试时需要部署空的数据库,除了数据库结构外,还需要将程序运行过程中所需要的基础数据创建好,以下存储过程,可一次性将基础数据写成insert语句,方便部署新库,使用时,传入表名即可。
这里用到了系统表syscolumns中的xtype字段,xtype具体含义如下:
34 image,35 text,36 uniqueidentifier,48 tinyint,52 smallint,56 int,58 smalldatetime,59 real,60 money,61 datetime,62 float,98 sql_variant,99 ntext,104 bit,106 decimal,108 numeric,122 smallmoney,127 bigint,165 varbinary,167 varchar,173 binary,175 char,189 timestamp,231 sysname,231 nvarchar,239 nchar。
利用这些数字识别将要插入字段的类型。用一下存储过程即可,注:该存储过程也将主键导出了。
-- ======================================================================
-- Description: 该存储过程返回的是参数表中的数据
-- ===========================================================================
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
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 (36,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
exec (@sql)
end
--spGenInsertSQL 表名
该存储过程来源于网上,我只是稍加更改,让GUID类型的字段也可以导出,希望对大家有所帮助哈~