1:
2: /****** Object: StoredProcedure [dbo].[sp_SQL_query_to_file_Row] Script Date: 05/29/2012 12:47:56 ******/
3: IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_SQL_query_to_file_Row]') AND type in (N'P', N'PC'))
4: DROP PROCEDURE [dbo].[sp_SQL_query_to_file_Row]
5: GO
6:
7:
8: create PROCEDURE sp_SQL_query_to_file_Row(
9: @servername varchar(50),@username varchar(50),@password varchar(50) ,
10: @filepath varchar(1000),@filename varchar(1000),
11: @SQL_query varchar(2000) ,@date varchar(20)
12: )AS
13: /*---------【版本信息】--------------------------------
14: 当前版本: 『 1.0 』
15: 创建人: 『 LiuJ 』
16: 完成日期: 『 2012-05-29 』
17: 修改人: 『 LiuJ 』
18: 修改日期: 『 2012-05-29 』
19: 优化建议: 『 』
20: -----------【功能及参数信息】---------------------------
21: 功能: 本存储过程的功能
22: 参数:
23: @servername varchar(50) --服务器名
24: @username varchar(50) --用户名 (如果用NT验证方式,则留空'')
25: @password varchar(50) --密码
26: @filepath varchar(1000) --导出路径
27: @filename varchar(1000) --导出文件名 (为''则默认时间戳为文件名)
28: @SQL_query varchar(2000) --要导出的文本内容
29: @date varchar(20) --保存文件时的生成日期戳 (为''则默认当前时间戳)
30:
31: ???? 中文的兼容性
32:
33: 备注:使用前需提升master表的执行权限:
34: ***********************************************************
35:
36: USE master
37: go
38: exec sp_configure 'show advanced options','1'
39: RECONFIGURE WITH override
40: go
41: exec sp_configure 'Ad Hoc Distributed Queries','1'
42: RECONFIGURE WITH override
43: go
44: exec sp_configure 'xp_cmdshell','1'
45: RECONFIGURE WITH override
46: go
47: ***********************************************************
48:
49: -----------【测试范例】---------------------------
50:
51: /*
52:
53: EXEC sp_SQL_query_to_file_Row '172.17.51.200 ','','','c:','test','testcon12345','20120525'
54:
55: */
56:
57: -----------------------------------------------------*/
58:
59: SET NOCOUNT ON
60:
61: declare @sql varchar(8000)
62: declare @dateStr varchar(20)
63: declare @outFileName varchar(250)
64: declare @serverInfo varchar(250)
65: set @sql =''
66: set @dateStr =''
67: set @outFileName =''
68: set @serverInfo =''
69:
70: set @datestr = convert(varchar(10),GETDATE(),12) + replace(convert(varchar(20),GETDATE(),24),':','')
71: if(ISNULL(@date,'') <>'')
72: begin
73: set @datestr = @date
74: end
75:
76: set @outFileName = @filepath + '\' + @filename + '_' + @datestr + '.txt'
77:
78: set @serverInfo = ' -S "' + + '" '
79: if((ISNULL(@username,'')) <>'')
80: begin
81: set @serverInfo = @serverInfo + ' -U "' + ltrim(rtrim(ISNULL(@username,''))) + '" -P "' + ltrim(rtrim(ISNULL(@password,''))) + '" '
82: end
83: else
84: begin
85: set @serverInfo = @serverInfo + ' -T '
86: end
87:
88:
89: set @SQL_query =REPLACE(@SQL_query,'''','''''')
90:
91: SET @SQL='bcp "select N'''+@SQL_query + '''" queryout ' + @outFileName + @serverInfo + ' -w '
92:
93: select @SQL
94:
95: EXEC master..xp_cmdshell @SQL
96:
97: IF @@Error<>0 BEGIN
98: print '生成文件时出错了,请查看!'+@@Error
99: END
100: GO
101:
102: