从T-SQL中创建Excel的XLS格式文件 T-SQL Excel XLS Create Excel XLS from T-SQLScript Rating Total number of votes [30] By: David A. Long This is a T-SQL script that uses OLE, ADO, Jet4 ISAM, and Linked Server to create and populate an Excel Wo
从T-SQL中创建Excel的XLS格式文件 T-SQL Excel XLSCreate Excel XLS from T-SQL Script Rating Total number of votes [30] By: David A. Long This is a T-SQL script that uses OLE, ADO, Jet4 ISAM, and Linked Server to create and populate an Excel Workbook (XLS) file from T-SQL query. If the Excel Worksheet exists, the query will append to the "table". The code is designed to be used by SQL Agent and to append to the step output with verbose and minimal detail. Code is pretty well commented, including some hard won knowledge about Jet4 ISAM, OLE, ADO, and usage of the Excel table from T-SQL -- Create XLS script DAL - 04/24/2003 -- -- Designed for Agent scheduling, turn on "Append output for step history" -- -- Search for %%% to find adjustable constants and other options -- -- Uses OLE for ADO and OLE DB to create the XLS file if it does not exist -- Linked server requires the XLS to exist before creation -- Uses OLE ADO to Create the XLS Worksheet for use as a table by T-SQL -- Uses Linked Server to allow T-SQL access to XLS table -- Uses T-SQL to populate te XLS worksheet, very fast -- PRINT 'Begin CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' ' PRINT '' GO SET NOCOUNT ON DECLARE @Conn int -- ADO Connection object to create XLS , @hr int -- OLE return value , @src varchar(255) -- OLE Error Source , @desc varchar(255) -- OLE Error Description , @Path varchar(255) -- Drive or UNC path for XLS , @Connect varchar(255) -- OLE DB Connection string for Jet 4 Excel ISAM , @WKS_Created bit -- Whether the XLS Worksheet exists , @WKS_Name varchar(128) -- Name of the XLS Worksheet (table) , @ServerName nvarchar(128) -- Linked Server name for XLS , @DDL varchar(8000) -- Jet4 DDL for the XLS WKS table creation , @SQL varchar(8000) -- INSERT INTO XLS T-SQL , @Recs int -- Number of records added to XLS , @Log bit -- Whether to log process detail -- Init variables SELECT @Recs = 0 -- %%% 1 = Verbose output detail, helps find problems, 0 = minimal output detail , @Log = 1 -- %%% assign the UNC or path and name for the XLS file, requires Read/Write access -- must be accessable from server via SQL Server service account -- & SQL Server Agent service account, if scheduled SET @Path = 'C:\TEMP\Test_'+CONVERT(varchar(10),GETDATE(),112)+'.xls' -- assign the ADO connection string for the XLS creation SET @Connect = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+@Path+';Extended Properties=Excel 8.0' -- %%% assign the Linked Server name for the XLS population SET @ServerName = 'EXCEL_TEST' -- %%% Rename Table as required, this will also be the XLS Worksheet name SET @WKS_Name = 'People' -- %%% Table creation DDL, uses Jet4 syntax, -- Text data type = varchar(255) when accessed from T-SQL SET @DDL = 'CREATE TABLE '+@WKS_Name+' (SSN Text, Name Text, Phone Text)' -- %%% T-SQL for table population, note the 4 part naming required by Jet4 OLE DB -- INSERT INTO SELECT, INSERT INTO valueS, and EXEC sp types are supported -- Linked Server does not support SELECT INTO types SET @SQL = 'INSERT INTO '+@ServerName+'...'+@WKS_Name+' (SSN, Name, Phone) ' SET @SQL = @SQL+'SELECT au_id AS SSN' SET @SQL = @SQL+', LTRIM(RTRIM(ISNULL(au_fname,'''')+'' ''+ISNULL(au_lname,''''))) AS Name' SET @SQL = @SQL+', phone AS Phone ' SET @SQL = @SQL+'FROM pubs.dbo.authors' IF @Log = 1 PRINT 'Created OLE ADODB.Connection object' -- Create the Conn object EXEC @hr = sp_OACreate 'ADODB.Connection', @Conn OUT IF @hr <> 0 -- have to use <> as OLE / ADO can return negative error numbers BEGIN -- Return OLE error EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc RETURN END IF @Log = 1 PRINT char(9)+'Assigned ConnectionString property' -- Set a the Conn object's ConnectionString property -- Work-around for error using a variable parameter on the Open method EXEC @hr = sp_OASetProperty @Conn, 'ConnectionString', @Connect IF @hr <> 0 BEGIN -- Return OLE error EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc RETURN END IF @Log = 1 PRINT char(9)+'Open Connection to XLS, for file Create or Append' -- Call the Open method to create the XLS if it does not exist, can't use parameters EXEC @hr = sp_OAMethod @Conn, 'Open' IF @hr <> 0 BEGIN -- Return OLE error EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc RETURN END -- %%% This section could be repeated for multiple Worksheets (Tables) IF @Log = 1 PRINT char(9)+'Execute DDL to create '''+@WKS_Name+''' worksheet' -- Call the Execute method to Create the work sheet with the @WKS_Name caption, -- which is also used as a Table reference in T-SQL -- Neat way to define column data types in Excel worksheet -- Sometimes converting to text is the only work-around for Excel's General -- Cell formatting, even though the Cell contains Text, Excel tries to format -- it in a "Smart" way, I have even had to use the single quote appended as the -- 1st character in T-SQL to force Excel to leave it alone EXEC @hr = sp_OAMethod @Conn, 'Execute', NULL, @DDL, NULL, 129 -- adCmdText + adExecuteNoRecords -- 0x80040E14 for table exists in ADO IF @hr = 0x80040E14 -- kludge, skip 0x80042732 for ADO Optional parameters (NULL) in SQL7 OR @hr = 0x80042732 BEGIN -- Trap these OLE Errors IF @hr = 0x80040E14 BEGIN PRINT char(9)+''''+@WKS_Name+''' Worksheet exists for append' SET @WKS_Created = 0 END SET @hr = 0 -- ignore these errors END IF @hr <> 0 BEGIN -- Return OLE error EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc RETURN END IF @Log = 1 PRINT 'Destroyed OLE ADODB.Connection object' -- Destroy the Conn object, +++ important to not leak memory +++ EXEC @hr = sp_OADestroy @Conn IF @hr <> 0 BEGIN -- Return OLE error EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc RETURN END -- Linked Server allows T-SQL to access the XLS worksheet (Table) -- This must be performed after the ADO stuff as the XLS must exist -- and contain the schema for the table, or worksheet IF NOT EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName) BEGIN IF @Log = 1 PRINT 'Created Linked Server '''+@ServerName+''' and Login' EXEC sp_addlinkedserver @server = @ServerName , @srvproduct = 'Microsoft Excel Workbook' , @provider = 'Microsoft.Jet.OLEDB.4.0' , @datasrc = @Path , @provstr = 'Excel 8.0' -- no login name or password are required to connect to the Jet4 ISAM linked server EXEC sp_addlinkedsrvlogin @ServerName, 'false' END -- Have to EXEC the SQL, otherwise the SQL is evaluated -- for the linked server before it exists EXEC (@SQL) PRINT char(9)+'Populated '''+@WKS_Name+''' table with '+CONVERT(varchar,@@ROWCOUNT)+' Rows' -- %%% Optional you may leave the Linked Server for other XLS operations -- Remember that the Linked Server will not create the XLS, so remove it -- When you are done with it, especially if you delete or move the file IF EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName) BEGIN IF @Log = 1 PRINT 'Deleted Linked Server '''+@ServerName+''' and Login' EXEC sp_dropserver @ServerName, 'droplogins' END GO SET NOCOUNT OFF PRINT '' PRINT 'Finished CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' ' GO

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software