How to export table structure and some data in SQL Server?

In SQL Server, you can export table structure and some data using the following methods:

  1. Export table structure:
    You can generate the CREATE statement of a table using the following SQL query, then save the generated SQL statement as a .sql file.
SELECT 
    'CREATE TABLE ' + TABLE_NAME + ' (' + 
        STUFF((
            SELECT ', ' + COLUMN_NAME + ' ' + DATA_TYPE + 
                CASE 
                    WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL THEN '(' + CONVERT(VARCHAR, CHARACTER_MAXIMUM_LENGTH) + ')' 
                    ELSE '' 
                END
            FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_NAME = tables.TABLE_NAME 
            ORDER BY ORDINAL_POSITION
            FOR XML PATH('')
        ), 1, 2, '') + ');'
FROM INFORMATION_SCHEMA.TABLES AS tables
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME;

Executing the above SQL statement will generate a .sql file containing the CREATE statements for the table structure.

  1. the table of mine
SELECT TOP 10 *
FROM my_table

After running the above SELECT statement, right-click on the results and choose “Result Set” -> “Result Set Options” -> “Save Results As” to save the results as a CSV file.

By using the above method, it is possible to export the structure and some data of tables in SQL Server.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds