SQLServer 导出数据insert语句

SET NOCOUNT ON
--表名和查询条件
DECLARE @TABLENAME VARCHAR(64),@C VARCHAR(512)
SET @TABLENAME='BA_ROLEAUTHORITY'
SET @C='WHERE 1=1'
--定义字段名,类型和长度的变量,以及获取表结构的游标
declare @name varchar(64),@type varchar(16),@len varchar(6)
declare tbCur cursor
for select COLUMN_NAME ,DATA_TYPE,CHARACTER_OCTET_LENGTH from INFORMATION_SCHEMA.COLUMNS
where table_name=@TABLENAME
--定义插入语句的变量
declare @rows nvarchar(512),@EXE_SQL nvarchar(2048),@sqlrow nvarchar(2048)
set @rows=''
set @EXE_SQL=''
--获取表结构,
open tbCur
fetch next from tbCur into @name,@type,@len
while @@FETCH_STATUS=0
begin
set @rows=@rows+@name+','
IF @type = 'varchar' or @type='char' or @type ='datetime' or @type='nvarchar' or @type ='nchar'
BEGIN
set @EXE_SQL=@EXE_SQL+ 'ISNULL(''N''''''+'+@name+'+'''''''',''NULL'')'+'+'',''+'
END
ELSE
BEGIN
set @EXE_SQL=@EXE_SQL+ 'ISNULL(CONVERT(VARCHAR(12),'+@name+'),''NULL'')'+'+'',''+'
END
fetch next from tbCur into @name,@type,@len
end
set @rows=SUBSTRING(@rows,1,len(@rows)-1)
set @EXE_SQL=SUBSTRING(@EXE_SQL,1,len(@EXE_SQL)-5)
close tbCur
deallocate tbCur

--EXEC('select '+@EXE_SQL+' from '+@TABLENAME +' '+@C)
--创建临时表
exec('select '+@EXE_SQL+' AS R into ##temp from '+@TABLENAME +' '+@C)
--定义要获取数据的游标
declare tb_cur cursor
for select * from ##temp
open tb_cur
fetch next from tb_cur into @sqlrow
while(@@FETCH_STATUS=0)
begin
print 'INSERT INTO '+@TABLENAME+'('+@rows+') VALUES('+@sqlrow+')'
fetch next from tb_cur into @sqlrow
end
close tb_cur
deallocate tb_cur
exec('drop table ##temp')

你可能感兴趣的:(数据库)