Sql Server 数据库表查询结果导出为excel文件
相信大家常常会遇到将SqlServer查询结果导出到Excel的问题。如果导出的次数少,直接Save Results As...就是了; 1.1准备好查询语句 1.2选择数据库,启动导入和导出向导 1.3选择数据源 1.4选择目标 1.5 1.6 1.7 1.8 后续步骤不再附图,一直点下一步按钮就好。
相信大家常常会遇到将SqlServer查询结果导出到Excel的问题。如果导出的次数少,,直接“Save Results As...”就是了;
1.1准备好查询语句
1.2选择数据库,启动导入和导出向导
1.3选择数据源
1.4选择目标
1.5
1.6
1.7
1.8
后续步骤不再附图,一直点“下一步”按钮就好。
2、但是当要分别在每个表取样,那就相当麻烦了。今天就为大家提供一个脱离office组件的可以将语句结果导出到Excel的过程,希望会对大家有帮助!
---导出到Excel
---使用说明:
-- 1.执行时所连接的服务器决定文件存放在哪个服务器
-- 2.远程查询语句中,要加上数据库名
ALTER PROC ExportFile
@QuerySql VARCHAR(max)
,@Server VARCHAR(20)
,@User VARCHAR(20)
,@Password VARCHAR(20)
,@FilePath NVARCHAR(100) = 'c:ExportFile.xls'
AS
DECLARE @tmp VARCHAR(50) = '[##Table' + CONVERT(VARCHAR(36),NEWID())+']'
BEGIN TRY
DECLARE @Sql VARCHAR(max),@DataSource VARCHAR(max)='';
--判断是否为远程服务器
IF @Server '.' AND @Server '127.0.0.1'
SET @DataSource = 'OPENDATASOURCE(''SQLOLEDB'',''Data Source='+@Server+';User;Password='+@Password+''').'
--将结果集导出到指定的数据库
SET @Sql = REPLACE(@QuerySql,' from ',' into '+@tmp+ ' from ' + @DataSource)
PRINT @Sql
EXEC(@Sql)
DECLARE @Columns VARCHAR(max) = '',@Data NVARCHAR(max)=''
SELECT @Columns = @Columns + ',''' + name +''''--获取列名(xp_cmdshell导出文件没有列名)
,@Data = @Data + ',Convert(Nvarchar,[' + name +'])'--将结果集所在的字段更新为nvarchar(避免在列名和数据union的时候类型冲突)
FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb..'+@tmp)
SELECT @Data = 'SELECT ' + SUBSTRING(@Data,2,LEN(@Data)) + ' FROM ' + @tmp
SELECT @Columns = 'Select ' + SUBSTRING(@Columns,2,LEN(@Columns))
--使用xp_cmdshell的bcp命令将数据导出
EXEC sp_configure 'xp_cmdshell',1
RECONFIGURE
DECLARE @cmd NVARCHAR(4000) = 'bcp "' + @Columns+' Union All ' + @Data+'" queryout ' + @FilePath + ' -c -T'
PRINT @cmd
exec sys.xp_cmdshell @cmd
EXEC sp_configure 'xp_cmdshell',0
RECONFIGURE
EXEC('DROP TABLE ' + @tmp)
END TRY
BEGIN CATCH
--处理异常
IF OBJECT_ID('tempdb..'+@tmp) IS NOT NULL
EXEC('DROP TABLE ' + @tmp)
EXEC sp_configure 'xp_cmdshell',0
RECONFIGURE
SELECT ERROR_MESSAGE()
END CATCH
先不要着急使用,该版本是基于xp_cmdshell的,因为要创建文件,所以要保证你的用户能有文件管理的权限,通常简单点的方法就是将sql server的启动用户设置为本地系统用户
好了,现在我们来执行看看:
--查询分析器连接哪个服务器,文件就在哪个服务器上
--本地导出
EXEC dbo.ExportFile @QuerySql = 'select * from sys.objects', -- varchar(max)
@Server = '.', -- varchar(20)
@FilePath = N'c:objects.xls' -- nvarchar(100)
--远程导出
EXEC dbo.ExportFile @QuerySql = 'select * from master.sys.objects', -- varchar(max)
@Server = '192.168.1.52', -- varchar(20)
@User = 'sa', -- varchar(20)
@Password = 'sa', -- varchar(20)
@FilePath = N'c:52objects.xls' -- nvarchar(100)
执行结果如下,显示导出条数,就没有报错,再看看你的C盘,多了2个文件就大功告成了:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

Original title: "These 3 Excel financial functions are undervalued again!" 》Author of this article: Xiaohua Editor of this article: Zhu Lan Recently, Xiaohua encountered an interesting question, which came from the soul of an old friend: How to choose between monthly annuity and private mutual insurance finance? The basic information of these two financial products is as follows: Monthly annuity: monthly payment of 1,000 yuan, annualized interest rate of 3%, 2-year term, and one-time withdrawal of principal and interest upon maturity. Mutual insurance finance: Pay a principal of 1,000 yuan every month, and the monthly principal will be calculated at 10% interest, with a 2-year term. There are 24 people participating in the same product. Every month, one person must receive all the principal and interest paid by others. The next month after receiving the payment, one person must pay an interest of 100 yuan/month. How to compare the pros and cons of these two financial products? we can
