How to Query CSV in SQL and Export Data Without the Headache

Última actualización: 10/14/2026
  • Azure Synapse serverless SQL can query CSV files directly with OPENROWSET, using parser options for headers, delimiters, line endings, quotes, and escapes.
  • SQL Server exports to CSV through SSMS wizards, result-set copy, sqlcmd, and BCP, while Bulk Insert and string_split help load delimited text back in.
  • Script-based export forms add parameter dialogs, column definitions, and BD4 scripting to control Excel and CSV output.
  • CSV quirks such as quoting, backslash escapes, accents, and thousands separators can change query results, so parser settings matter.

Servidor de datos en un centro de cómputo moderno con iluminación azul, representando la infraestructura de base de datos SQL.

CSV files look boring at first glance, but they are one of the most flexible ways to move data between SQL databases, spreadsheets, cloud storage, and custom applications. If you need to query a CSV in SQL, you are not limited to importing it first; modern engines such as Azure Synapse serverless SQL pools can read the file directly from a URL or an external data source. At the same time, SQL Server gives you several reliable ways to push data the other direction, from tables and query results into CSV files. This article pulls together those workflows, plus the quirks that can make CSV parsing feel like a puzzle.

The trick is knowing which tool fits the job. Sometimes OPENROWSET is all you need, especially when the CSV lives in Blob Storage and you want to inspect it quickly. Other times you need the SSMS import/export wizard, the sqlcmd utility, BCP, Bulk Insert, string_split, or even a scripted export form that lets users define their own queries. Along the way, details such as headers, line endings, quote characters, escape characters, and thousands separators can decide whether your query returns clean rows or a mess. The sections below walk through all of that in a practical, hands-on way.

Querying CSV Files Directly with Azure Synapse Serverless SQL

Profesional analizando datos en una hoja de cálculo en un ordenador portátil, ilustrando el manejo de archivos CSV.

Azure Synapse Analytics offers a serverless SQL pool that can query a single .csv file without loading it into a table. The star of that show is OPENROWSET, a function that reads file content when you give it a URL or a data source path. CSV files come in many shapes: with or without a header row, comma-delimited or tab-delimited, Windows-style or Unix-style line endings, quoted or unquoted values, and with or without escape characters. A good query has to account for all those variations.

For a quick start, hand OPENROWSET the full URL of the CSV. Specify FORMAT = ‘CSV’ and PARSER_VERSION = ‘2.0’ so the engine knows what kind of file it is dealing with. If the file is publicly available, or if the Microsoft Entra identity has access, you can immediately select from it. A typical query looks like this:

SELECT TOP 10 * FROM OPENROWSET( BULK 'https://pandemicdatalake.blob.core.windows.net/public/curated/covid-19/ecdc_cases/latest/ecdc_cases.csv', FORMAT = 'CSV', PARSER_VERSION = '2.0', FIRSTROW = 2 ) AS rows;

That FIRSTROW option is a simple but powerful trick. It skips the first row, which is usually the header, so the result set starts with actual data. Before you run the query, make sure you can reach the file. If the file is protected by a SAS key or a custom identity, you need to configure credentials at the server level for the SQL login. Without that access, OPENROWSET will complain even if the syntax is perfect.

Instead of repeating the full path every time, create an external data source that points to the root folder of the storage. That keeps your queries shorter and easier to maintain. For example, you can define a source named covid with a location such as https://pandemicdatalake.blob.core.windows.net/public/curated/covid-19/ecdc_cases. After that, OPENROWSET can use a relative path like latest/ecdc_cases.csv together with DATA_SOURCE = ‘covid’. If the data source is protected by a SAS key or a custom identity, set up database-scoped credentials as well.

When you already know the columns you want, use the WITH clause to declare an explicit schema. The numbers after each data type tell SQL the ordinal position of the column in the CSV file. For example, WITH (date_rep date 1, cases int 5, geo_id varchar(6) 8) means date_rep comes from column 1, cases from column 5, and geo_id from column 8. This is useful when the file has extra columns you do not care about, or when you want to apply proper data types instead of letting the engine guess.

Before running the examples, you normally need a database and a setup script. The script creates data sources, database-scoped credentials, and external file formats that the queries rely on. Once those objects exist, you can test different CSV layouts. For a Windows-style newline with no header row and comma-delimited columns, the query might use FIELDTERMINATOR = ‘,’ and ROWTERMINATOR = ‘\n’, then declare country_code, country_name, year, and population in the WITH clause. A filter such as WHERE country_name = ‘Luxembourg’ AND year = 2017 keeps the result focused.

Unix-style line endings need a different row terminator. In many cases you set ROWTERMINATOR = ‘0x0a’, which represents the line feed character. The file path may also be different from the Windows example. If the Unix-style file includes a header row, you can avoid writing a full WITH clause by using HEADER_ROW = TRUE. That option reads column names from the first row, which is great for exploration when you are not yet familiar with the file contents. For the best performance, though, it is still wise to switch to explicit data types later.

Quoted values need a custom quote character. FIELDQUOTE = ‘"’ tells the parser that double quotes wrap values, which prevents commas inside those values from being treated as column separators. You might combine that with FIRSTROW = 2, ROWTERMINATOR = ‘0x0a’, FIELDTERMINATOR = ‘,’, and a WITH clause for the columns you need. Again, a WHERE clause can narrow the result to a specific country and year.

Escape characters are another common headache. If the file uses a backslash to escape a field delimiter, use ESCAPECHAR = ‘\’ in the OPENROWSET options. That tells the parser not to treat the escaped comma as a real separator. You can still combine it with FIELDTERMINATOR, ROWTERMINATOR, FIRSTROW, and a WITH schema. There are also files where double quote characters are escaped between values; those may require careful use of quoting options or a parser version that handles the pattern correctly.

Tab-delimited files are just another variation. Set FIELDTERMINATOR = ‘\t’ and keep the rest of the options consistent, such as ROWTERMINATOR = ‘0x0a’, FIRSTROW = 2, and the column definitions in WITH. The file path is usually different from the comma-delimited examples, so double-check the BULK path or the relative path under your data source.

You do not always need every column. If you only want a count of distinct country names, specify just that column in the WITH clause and comment out the rest. The ordinal number after the data type is the only column reference the parser needs. For example, you can define country_name VARCHAR(100) as column 2 and omit country_code, year, and population. That reduces parsing work and keeps the query readable.

Appendable CSV files require special care. A CSV file should not change while a query is running. In a long-running query, the SQL pool may retry reads, read parts of files, or even read the same file multiple times. If the file content changes during execution, you can get incorrect results, so the pool raises an error when it detects that the modification time changed. For files that are constantly appended, you can use ROWSET_OPTIONS = ‘{"READ_OPTIONS":["ALLOW_INCONSISTENT_READS"]}’. That disables the modification-time check during the query lifecycle and reads whatever is available. Because append-only files do not update existing content, the risk of wrong results is lower than with updatable files. In most scenarios, the SQL pool simply ignores some rows that were added while the query was running.

What Makes CSV So Useful for SQL Workflows

CSV stands for comma-separated values, and it has been around so long that almost every data tool speaks the language. Excel, Calc, many IDEs, and database servers can all import or export CSV files, which makes the format a universal handshake between systems. A CSV file is usually plain text: each line is a row, and commas separate the values. The first line often holds column headers, such as id, first_name, and last_name, while the following lines contain the matching values.

The simplicity is exactly why people keep coming back to it. You can open a CSV in a spreadsheet program and read it like a table, or process it with a script, or load it into a database. That human-readable quality matters when you need to debug a data exchange, share a quick sample with a colleague, or move information between Windows and Linux without worrying about proprietary formats. Companies that run different platforms can use CSV as a common ground for import and export.

For SQL users, the usual scenario is simple: you have a table or query result, and you want to get it out of the database so another application can consume it. Exporting to CSV is often faster and less complicated than building a full integration. The destination might be Excel for a business report, a Python script for analysis, or another database that will ingest the file later. The same logic applies in reverse when you want to query a CSV in SQL: the file may have arrived from an external partner, a cloud export, or a log process.

Consider a product table with columns id, name, and category. The rows might include a keyboard in electronics, bricks in toys, a lamp in electronics, a wood car in toys, and a ball in toys. A simple SELECT * FROM product shows everything inside the SQL output window, but that is not much help if the request is to open the same data in Excel. That is where the export methods below come in.

Exporting SQL Server Data to CSV: Five Practical Routes

Monitor con código SQL legible utilizando la función OPENROWSET para consultar un archivo CSV.

SQL Server does not have a single magic button labeled export to CSV for every situation. You can use a graphical wizard, a result-set shortcut, a command-line utility, or a bulk copy tool, and the right choice depends on whether you want automation, headers, or a one-off manual export. The five routes below cover the most common needs.

Method 1: SQL Server Management Studio Export Wizard

The first route uses SSMS, Microsoft’s graphical tool for managing SQL Server objects and data. It is a good fit when you prefer clicking through options instead of writing commands. Start SSMS from the Windows Start menu by expanding Microsoft SQL Server Tools and selecting Management Studio. Then expand the Databases node, right-click the database that contains your table, and choose Tasks, followed by Export Data.

The Import and Export Wizard appears. Click Next, and on the data source screen choose SQL Server Native Client. Fill in the server name, user name, password, and the database that stores the table you want to export. In the product example, that database might be called store. Continue to the destination screen and choose Flat File as the target format for a CSV file. Provide the file name, location, and code page, then check the boxes for Unicode and column names if you want a header row and broad character support.

Next, decide whether to copy all data from the table or write a SQL query. The first option is usually enough when the whole table is the export target. Select the product table from the list, keep clicking Next through the remaining screens, and finally click Finish. SSMS shows a success or error summary. Close the wizard and look for the generated file in the user folder or the location you specified.

Method 2: Save SSMS Result Set Without Column Names

Another SSMS-based approach starts with a query result. It is fast and convenient when you already have the data on screen. In Object Explorer, expand the database that contains the product table, click New Query, and run SELECT * FROM product. The result set displays all rows. Right-click inside the data rows and choose Save Results As. Pick a destination folder, enter a file name such as producto-tienda, and confirm. The resulting CSV contains the data, but it does not include column names.

Method 3: Copy SSMS Result Set With Headers

If you want headers, use a close variation of the previous method. Right-click the result set and choose Select All, which highlights every row. Then right-click the selected rows and choose Copy with Headers. Open an empty CSV file and paste the clipboard content. You now have both the column names and the data in a format that spreadsheet software can read immediately.

Method 4: Export with the sqlcmd Utility

sqlcmd is a command-line tool that runs SQL statements or scripts from a terminal. It is ideal when you want repeatable exports or need to schedule a job. Open Command Prompt and run a command that includes the server, query, separator, output file, and authentication option. A typical command looks like sqlcmd -S DESKTOP-INGEKE8\MSSQLSERVER,1433 -Q ‘select * from store.dbo.product’ -s ‘,’ -o ‘C:\Users\dora\Documents\products_list.csv’ -E.

Here is how to read that command. The first token is the tool name, sqlcmd. The -S option is followed by the server name, a backslash, the SQL Server instance name, a comma, and the port number; the default port is often 1433. The -Q option contains the SELECT statement inside quotes. In the example, store is the database, dbo is the default schema, and product is the table. The -s option, in lowercase, sets the column separator; a comma inside quotes means comma-separated output. The -o option gives the output path and file name. Finally, -E means a trusted connection to the database server. After execution, the CSV file appears at the specified path with the product data inside it.

You may also see BCP-style commands mixed into sqlcmd discussions. For example, bcp store.dbo.product out C:\Users\dora\Desktop\product-data.csv -S DESKTOP-INGEKE8\SQLEXPRESS -c -t ‘,’ -T, or bcp ‘SELECT * from product WITH (NOLOCK)’ queryout c:\product-store.csv -c -T. Those are not sqlcmd statements, but they belong to the same command-line family and are often used side by side when exporting data.

Method 5: Use the BCP Utility

BCP is a bulk copy program that moves data between a SQL instance and a data file. It is built for speed and automation, which makes it a natural fit for large exports. Open Command Prompt and run a command such as bcp store.dbo.product out C:\Users\dora\Desktop\product-data.csv -S DESKTOP-INGEKE8\MSSQLSERVER,1433 -c -t ‘,’ -T. The first token, bcp, is followed by the database, schema, and table names separated by periods. The out keyword specifies the result file path. The -S option gives the server and instance, with the port after a comma; port 1433 is the common default. The -t option, in lowercase, defines the separator inside quotes, which is a comma here. The -T option, in uppercase, uses trusted Windows authentication.

When the command runs, BCP prints status messages that tell you how the copy is progressing. That feedback is useful when you are moving many rows or testing a new destination path. Once it finishes, the CSV file contains the exported table data. With these five routes, you can export a SQL Server table or query result to CSV using the method that best matches your comfort level and automation needs.

Reading Delimited Text into SQL with Bulk Insert and string_split

Exporting is only half the story. Sometimes the CSV or delimited text file already exists, and you need to pull it into SQL Server. Bulk Insert is a straightforward way to load the raw file into a temporary table, often as a single column. From there, functions such as string_split can break each line into separate values. This pattern came up in a TechNet question about reading a text file in SQL and inserting it into a table, and it is still useful today.

Start by creating a text file. For example, place a file named archivo.txt in C:\ejemplo with three lines: juan;alvarez;5, ana;lis;12, and bea;redejo;13. There are no headers and only three rows. In SQL Server Management Studio, run a dynamic query that uses Bulk Insert with the simplest parameters. After execution, a temporary table holds three rows and one column. A query such as SELECT * FROM #tempData returns those three semicolon-delimited strings exactly as they appeared in the file.

The next phase is to split each row. string_split can turn one delimited string into multiple values, but you should be careful about order. If you need to pivot the values back into columns, number the resulting rows with ROW_NUMBER. That numbering becomes the anchor for the next step: collecting only the value column for each row so that you end up with three rows and three columns. Then pivot the extracted content to produce a result set that can be inserted directly into a new table.

The pivot logic usually sits inside a derived table, sometimes called source. For each row, a ROW_NUMBER value of 1 becomes column one, 2 becomes column two, and 3 becomes column three. Running the full query returns a three-by-three table, which was the original goal. If a destination table already exists, you only need to wrap the query with an INSERT statement. That is the clean, happy-path version of the process.

Real files are rarely that polite. Suppose the input contains missing values, extra delimiters, or malformed rows. A simple CASE expression can supply default values for absent columns, which keeps the insertion from failing. If someone accidentally removes a semicolon, the file structure can fall apart. For example, a line that should have three fields might arrive as ana;12. By using ISNUMERIC and related checks, you can avoid breaking the whole load and still insert a reasonable row. It is not perfect data cleaning, but it prevents a small defect from derailing the entire process.

There is another catch: string_split does not guarantee the order of its output. In high-volume scenarios where the engine uses parallelism, unpredictable ordering can ruin the row-to-column mapping. A safer approach is to use a split function that returns values in order. One well-known solution comes from Itzik Ben-Gan and appears in many developments and books, including preparation material for the 70-761 certification exam, Querying Data with Transact-SQL. The first function returns a range of numbers between a low and a high parameter. The second function uses that range to split the string in a deterministic order. If the code looks dense at first, break it into smaller pieces and test each part; the concept is worth understanding.

Building a Form-Based SQL Export Tool for Excel and CSV

Análisis de datos con gráficos estadísticos en la pantalla de un portátil, mostrando el resultado de una consulta SQL sobre datos CSV.

Not every export has to be a manual query. Some applications provide a form where users define SQL queries, run them with parameters, and save the result as Excel or CSV. This kind of tool is helpful when business users need controlled access to data without writing SQL themselves. The form usually has a Realizar button; when pressed, it opens a dialog with the parameters defined in the query, and an Aceptar button runs the query and saves the output to the chosen file format.

The form includes several key fields. The file field expects a name without an extension, which becomes the default name for the Excel or CSV result. The description field is optional and can hold help text for users. The SQL statement field accepts either a SQL statement or a BD4 script. There is also a users table with permission: any non-administrator who is neither DBA nor ADMIN must be registered there before they can execute the query.

Parameters are defined in their own table. Each parameter needs a number that matches the SQL query, a display name, and a type such as string, integer, decimal, date, time, or boolean. You also set the field size shown in the dialog, whether nulls are allowed, and a default value that stores what the user entered the last time the query ran. When the user opens the dialog, these definitions control what they can type and which values are mandatory.

Columns are defined in another table. That table controls the order and appearance of the resulting Excel or CSV file. Each column has a number for ordering, a display name, and a type such as string, integer, decimal, date, time, boolean, or script. The column-of-statement field maps the output column to an index in the SQL query; it can be left blank when the result should be a constant default value, null, or a script value. If the column type is script, the default value must be the name of a function in the script. If the columns table is empty on the next execution, the tool can calculate the columns automatically.

The form menu also supports importing and exporting query definitions. These utilities are meant for copying queries between different databases, not for long-term archiving. An exported file may be incompatible with future versions, so a query exported from an older version might not import cleanly later.

BD4 script is the scripting layer behind this kind of form. It is very similar to JavaScript and also lets you interact with Java objects. You can call BD4 script functions from Java, and Java can call them back. The class that runs the script can define which objects are allowed to be created or obtained. One important syntax difference: the == operator is equivalent to Java’s equals method, so you should use == and != instead of === and !==, which are not allowed. Every statement must end with a semicolon.

There are several language rules to remember. Functions can only be defined through statements in the main program, so you cannot assign a function to a variable. You can only use variables and constants that were declared earlier. Functions can access variables and constants from the main program, and those are the only ones they can redefine. A variable declared in one scope cannot be redefined in a nested scope. Uninitialized variables contain null, and there is no undefined value. The language supports 32-bit integers, strings, booleans, and all Java object types. Arrays and hash tables are Java objects, and the bracket operator accesses their elements. In a sense, a script acts like a class: the main program variables hold its internal state, and its functions form the interface.

Several special functions can be defined in a script. queryGetSQL must return the SQL query, and it is required if the query text is treated as a script. If it returns null or nothing, you must define queryHasNext and queryNext. querySetParameters is needed when the parameters defined in the form do not match the SQL statement parameters; it uses setParameter to pass values. queryHasNext returns true when data is available, and queryNext prepares the next row. Those two functions must be defined together, and they are only necessary when the query result rows do not map directly to the rows written to Excel or CSV, such as when you need a summary, or when queryGetSQL returns null.

The script can call a set of built-in helpers. assert checks that a boolean expression is true. getConnection returns the database connection and takes no parameters. getParameter returns a value from the dialog by index. setParameter changes a SQL statement parameter by index and value. getObject returns an object from the query result by column name. getString returns a string from the query result with a maximum size. hasNext returns true if another row is available. next prepares the following row. These functions make it possible to build dynamic queries, inspect results, and transform rows before export.

You can also create Java objects with the new operator. Array creates an array or a two- or three-dimensional matrix, depending on how many integer dimensions you pass; new Array(3,4), for instance, creates three rows and four columns. ArrayList creates a dynamic array and can accept initial objects. BigDecimal creates a decimal from a string. CsvFileInput reads a CSV file. Error creates a RuntimeException with an optional description. GregorianCalendar handles date calculations. HashMap and HashSet are the usual hash-based structures. Integer creates an integer from a string. LinkedHashMap and LinkedHashSet keep a linked list to preserve iteration order. LinkedList creates a linked list. SQLQuery creates a SQL query. StringBuilder creates a mutable character sequence. StringTokenizer extracts tokens from a string. TreeMap works like a hash table but sorts keys using a red-black tree.

Control statements follow familiar patterns. while and for loops are available, along with continue to skip to the next iteration and break to exit a loop or case. if works like Java, and the ternary operator takes the form condition ? true_value : false_value. switch is also supported. Predefined constants include Arrays, BigDecimal, Calendar, Character, Collections, Integer, Json, Math, and RoundingMode, mapped to their Java packages. Exceptions are thrown with throw and handled with try, catch, and finally, just like Java. If an exception is not caught, the script stops. For example, throwing a test string inside a try block, catching it and printing the message, then running a finally block would print the error text followed by finally.

Small code examples show how the pieces fit together. A recursive Fibonacci function can use the ternary operator. An array-based version can allocate new Array(n + 1), set the first two values, and fill the rest in a loop. An ArrayList version can start with 0 and 1, then grow the list. A BigDecimal example can divide 100 by 3 with two decimal places and RoundingMode.HALF_UP, then compare the result to 33.33 and throw an error if it does not match. These examples are short, but they illustrate the scripting style used by the export form.

CSV Parsing Options You Should Know

CSV looks simple until it is not. Different tools make different assumptions about quoting, escaping, and number formatting, and those assumptions can change how a file is interpreted. When you query CSV in SQL or load it into another system, check whether the parser lets you replace accents and diacriticals, treat all quoting characters as data, or treat an apostrophe as the quoting character. Those options matter when names contain special characters or when a field legitimately includes quote marks.

Backslash escaping is another common setting. A file may contain sequences such as \n, \t, and \, that should be read as escape codes rather than literal characters. If the parser does not understand them, you can end up with broken rows or unexpected column separators. Similarly, thousands separators can be auto-detected in several styles: 1,234.56 for US or UK conventions, 1.234,56 for many European locales, 1 234,56 when a space is the thousands separator and a comma is the decimal marker, and 1 234.56 for space-and-dot formatting. Some parsers also let you disable thousands separators entirely. Choosing the right option prevents numbers from being treated as strings or split into multiple columns.

From cloud-native OPENROWSET queries in Azure Synapse to SSMS wizards, sqlcmd, BCP, Bulk Insert, string_split, and form-based export tools, the relationship between SQL and CSV is a two-way street. The same format that makes data easy to share also introduces edge cases around headers, delimiters, line endings, quotes, escapes, and locale-specific numbers. If you take the time to define schemas, set parser options, and choose an ordered splitting strategy when order matters, you can move data between SQL Server, Excel, cloud storage, and custom applications with far fewer surprises. Whether you are exploring a CSV directly from a Blob Storage URL or exporting a product table for a colleague, the right combination of SQL features and CSV awareness will keep your data flowing cleanly.

Related posts: