相信大家常常会遇到将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个文件就大功告成了:

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

The main reasons for slow MySQL query include missing or improper use of indexes, query complexity, excessive data volume and insufficient hardware resources. Optimization suggestions include: 1. Create appropriate indexes; 2. Optimize query statements; 3. Use table partitioning technology; 4. Appropriately upgrade hardware.

MySQL view is a virtual table based on SQL query results and does not store data. 1) Views simplify complex queries, 2) Enhance data security, and 3) Maintain data consistency. Views are stored queries in databases that can be used like tables, but data is generated dynamically.

MySQLdiffersfromotherSQLdialectsinsyntaxforLIMIT,auto-increment,stringcomparison,subqueries,andperformanceanalysis.1)MySQLusesLIMIT,whileSQLServerusesTOPandOracleusesROWNUM.2)MySQL'sAUTO_INCREMENTcontrastswithPostgreSQL'sSERIALandOracle'ssequenceandt

MySQL partitioning improves performance and simplifies maintenance. 1) Divide large tables into small pieces by specific criteria (such as date ranges), 2) physically divide data into independent files, 3) MySQL can focus on related partitions when querying, 4) Query optimizer can skip unrelated partitions, 5) Choosing the right partition strategy and maintaining it regularly is key.

How to grant and revoke permissions in MySQL? 1. Use the GRANT statement to grant permissions, such as GRANTALLPRIVILEGESONdatabase_name.TO'username'@'host'; 2. Use the REVOKE statement to revoke permissions, such as REVOKEALLPRIVILEGESONdatabase_name.FROM'username'@'host' to ensure timely communication of permission changes.


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

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!
