下面为您介绍的这个SQL Server存储过程,实现功能是将表内每两人之间相互通信内容区分开来,并分别写入文件,希望对您学习SQL Server存储过程方面能有所帮助。
--主过程(查找数据,并分类写入文件)
- CREATE PROC creatFileByNameProc
- @filepath varchar(128)
- as
- begin
- declare
- @fulFileName nvarchar(256),
- @content nvarchar(2000),
- @root nvarchar(64),
- @str2 nvarchar(64),
- @str3 nvarchar(64),
- @target nvarchar(64),
- @str5 nvarchar(64),
- @str6 nvarchar(64),
- @str7 nvarchar(64),
- @str8 nvarchar(64)
--文件是否存在的判断参数
- declare @isExist int, @filename1 nvarchar(256),@filename2 nvarchar(256)
--文件操作参数
- declare @obj int
- exec sp_oacreate 'Scripting.FileSystemObject',@obj out
- Declare MyCursor Cursor Scroll
- For Select [1],[2],[3],[4],[5],[6],[7],[8] From dbo.[1111] order by [7]
- Open MyCursor
- FETCH first from MyCursor into @root,@str2,@str3,@target,@str5,@str6,@str7,@str8
- while @@fetch_status=0
- Begin
- set @content= @root+' '+@str2+' '+@str3+' '+@target+' '+@str5+' '+@str6+' '+@str7+' '+@str8
- --print @content
- set @filename1= @target+'_'+ @root+'.txt'
- set @filename2= @root+'_'+@target+'.txt'
- set @isExist= dbo.[FileExist]( @filepath +'\' , @filename1)
- --- print @isExist
- if(@isExist=1)
- begin
- set @fulFileName=@filepath+'\'+@filename1
- --print @fulFileName+'---1111111'
- exec p_movefile @fulFileName,@content,@obj
- end
- else
- begin
- set @fulFileName=@filepath+'\'+@filename2
- --print @fulFileName+'---22222'
- exec p_movefile @fulFileName,@content,@obj
- end
- FETCH next from MyCursor into @root,@str2,@str3,@target,@str5,@str6,@str7,@str8
- END
- CLOSE MyCursor
- DEALLOCATE MyCursor
- end
--判断文件是否存在的函数
- create function dbo.FileExist(
- @filePath nvarchar(600),
- @fileName nvarchar(400)
- ) returns int
- as
- begin
- declare @result int
- declare @sql nvarchar(1000)
- set @sql=@filePath+@fileName
- exec master.dbo.xp_fileexist @sql,@result output
- return @result
- end
--文件不存在,创建文件,写入内容;文件存在,追加内容
- create proc p_movefile
- @filename varchar(1000),--要操作的文本文件名
- @text varchar(8000), --要写入的内容
- @obj int
- as
- begin
- declare @err int,@src varchar(255),@desc varchar(255)
- exec @err=sp_oamethod @obj,'OpenTextFile',@obj out,@filename,8,1
- if @err<>0 goto lberr
- exec @err=sp_oamethod @obj,'WriteLine',null,@text
- if @err<>0 goto lberr
- exec @err=sp_oadestroy @obj
- return
- lberr:
- exec sp_oageterrorinfo 0,@src out,@desc out
- select cast(@err as varbinary(4)) as 错误号
- ,@src as 错误源,@desc as 错误描述
- end
--执行语句。(由于没有进行文件夹是否存在的处理,执行前需要指定好已存在路径)
- exec creatFileByNameProc 'E:\aa'
【编辑推荐】