Creating dynamically generated CSV files containing SQL Server data

Creating dynamically generated CSV files containing SQL Server data

Creating dynamically generated CSV files containing SQL Server data

SQLShack

SQL Server training Español

Creating dynamically generated CSV files containing SQL Server data

February 12, 2015 by Steve Simon

Introduction

A few months back, I presented a paper at SQL Saturday 327 in Johannesburg, South Africa. Late last month I received an email from one of the attendees. His issue was quite interesting and I decided to share it with you. The gentleman wanted a SSIS script that would permit him to extract data from a SQL Server database table and place it in a CSV file with a dynamically allocated name. Being a strong advocate of using the SSIS toolbox, I experimented with an alternative solution. We are going to construct THIS SOLUTION in today’s get together. Let’s get started.

Getting Started

As our point of departure, we shall once again utilize our ‘SQLShackFinancial” database. We shall utilize data from the FASB table (see below). Our end goal is to obtain the following output: The astute reader will note that the csv file name contains the date and time on which the file was created. Opening Visual Studio we begin by creating a new Integration Services project. We select New and Project (see above). We select an Integration Services project and give our project a name. We click OK to create the project. We find ourselves on our Integration Services project workspace (see above). Our first task is to create a data connection to our SQLShackFinancial database.

Creating the database connection

We begin by right clicking in the “Connection Manager” box and selecting a “New OLE DB Connection” (see above). The “Configure OLE DB Connection Manager” dialogue box is brought up. We select “New” (see above). The “Connection Manager” dialogue box is now brought up and we configure this box as shown above. Testing the connection, we find that we are ready to go. We now add a Data Flow Task to our work surface (see below). Double clicking on the “Data Flow Task” we are brought into the “Data Flow Task” designer (see below). We now add an “OLE DB Data Source” to our work surface (see below). Double clicking on the “OLE DB Source” brings up the “OLE DB Source Editor” dialogue box. We configure our connection manager to point to the FASB table (see above). The columns tab shows the data columns within the table (see above).

Adding and configuring the destination csv file

We are now in a position to add the destination flat file which will contain the table data in a csv format. We drag a “Flat File Destination” control onto our work surface (see above) and join the “OLE DB” data source to the “Flat File” destination (see below). Double clicking the control brings up the “Flat File Destination” editor (see above). We click “New” to create a new connection. The “Flat File Format” dialogue box is brought into view (see above and to the left). We accept the “Delimited” radio button. Click OK. The “Flat File Connection Manager Editor” is then brought up. We are asked for a “Description” (which is optional) but more importantly we are asked for an output file name. We give our output file the name “FASB_” and set its type to csv (see above). We click “Open”. Clicking the “Columns” tab, we see that the fields from our table are visible. We click OK to exit this dialogue box and then click on the “Mappings” tab to configure the source to the destination (see below). We click OK to exist the “Flat File Destination Editor”. We now find ourselves back on our working surface. THE ISSUE is that in creating the flat csv file we have hard-wired the file name is this is NOT what we want.

Creating a dynamic file name for our output file

We begin by right clicking on our output file connection and bringing up its “Properties” box (see above and to the bottom right). We scroll down to find the “Expressions” property (see above and to the bottom right). Clicking on the “Expressions” ellipsis the “Property Expresssion Editor” is brought up(see above). We select the “Connectionstring” Property from the “Property” dropdown list (see above) and click upon the “Expression” box. The “Expression Builder” dialogue box is brought into view (see above). In the “Expression” box, we enter the following code snippet. Adding a time component (to the string) enables us to produce multiple daily extracts. 123456789 "C:\\SQLShack\\FASB_" +Right("0" + (DT_STR,4,1252) DatePart("m",getdate()),2) +Right("0" + (DT_STR,4,1252) DatePart("d",getdate()),2) + (DT_STR,4,1252) DatePart("yyyy",getdate()) + "_"+ (DT_STR,2,1252) DatePart("hh",getdate()) +"_"+ (DT_STR,2,1252) DatePart("n",getdate()) + ".csv" The astute reader will note that when we “Evaluate” the expression (see above) that the fully qualified file name appears in the “Evaluated value” box. Further we must note the usage of two “\\” for every one that we wish to appear in the file “Evaluated” path and file name. FORTRAN and COBOL programmers will remember this one! We click OK to leave the “Expression Builder” and OK to leave the “Property Expressions Editor” (see above). We find ourselves back on our work surface (see above).

Let us give our package a whirl

We click the “Debug” tab on the top ribbon and select “Start Debugging” (see above). The process completes successfully. Our extract file may be seen in the screen dump above. Note that the file name contains the run date and time of the process. Opening the comma delimited file in Notepad, we see the data in a comma delimited form.

Conclusion

Oft times we find that we have external processes that require extracts of data from our tables. In some cases the final format must be in CSV format. In this “get together” we have constructed a quick and dirty process to pull data from a database table and to place the data into a flat csv file IN ADDITION to providing a mechanism to run the process throughout the day. Should you wish the code for this article, please feel free to contact either the SQLShack editor or me. In the interim, happy programming. Author Recent Posts Steve SimonSteve Simon is a SQL Server MVP and a senior BI Development Engineer with Atrion Networking. He has been involved with database design and analysis for over 29 years.

Steve has presented papers at 8 PASS Summits and one at PASS Europe 2009 and 2010. He has recently presented a Master Data Services presentation at the PASS Amsterdam Rally.

Steve has presented 5 papers at the Information Builders' Summits. He is a PASS regional mentor.

View all posts by Steve Simon Latest posts by Steve Simon (see all) Reporting in SQL Server – Using calculated Expressions within reports - December 19, 2016 How to use Expressions within SQL Server Reporting Services to create efficient reports - December 9, 2016 How to use SQL Server Data Quality Services to ensure the correct aggregation of data - November 9, 2016

Related posts

How to Avoid Package Design Flaws When Sourcing Data From Flat Files Using SSIS packages to import MS Excel data into a database How to import data into SQL Server databases using the OData source for SQL Server Integration Services Creating reports based on existing stored procedures with SQL Server Reporting Services How to import flat files with a varying number of columns in SQL Server 77,279 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ▼Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ►Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ►Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!