---1、开启xp_cmdshell选项;基于安全的考虑,系统默认没有开启xp_cmdshell选项
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
GO
---2、查询服务名
SELECT serverproperty('servername')
---3、导出表至EXCEL(类Excel,虽然格式是xls,但不受行数限制,且为只读,若修改需另存为Excel)
EXEC master..xp_cmdshell 'bcp 数据库.dbo.表 out c:\Temp.xls -c -q -S"服务名" -U"用户名" -P"密码"'
---示例
--EXEC master..xp_cmdshell 'bcp "select ''月份'',''编码'',''名称'',''住院号'',''姓名'',''生日'',''入院日期'' union all select convert(varchar(20),month,120) ,code ,name,hospital_no ,person_name ,convert(varchar(20),birthday,120),convert(varchar(20),in_date,120) from drgsdb_ggrm.dbo.drg_record" queryout c:\病案数据.xls -c -q -S"YCW-PC" -U"sa" -P"system"'
---4、关闭sp_cmdshell选项
EXEC sp_configure 'show advanced options', 1
RECONFIGURE;
GO
EXEC sp_configure 'xp_cmdshell', 0
RECONFIGURE;
GO