02 January 2023

MS SQL - Generate insert script for selected records

If possible use Visual Studio. The Microsoft SQL Server Data Tools (SSDT) bring a built in functionality for this since the March 2014 release:
  1. Open Visual Studio
  2. Open "View" → "SQL Server Object Explorer"
  3. Add a connection to your Server
  4. Expand the relevant database
  5. Expand the "Tables" folder
  6. Right click on relevant table
  7. Select "View Data" from context menu
  8. In the new window, viewing the data use the "Sort and filter dataset" functionality in the tool bar to apply your filter. Note that this functionality is limited and you can't write explicit SQL queries.
  9. After you have applied your filter and see only the data you want, click on "Script" or "Script to file" in the tool bar
  10. Voilà - Here you have your insert script for your filtered data

Notes:
  1. Be careful, the "View Data" window is just like SSMS "Edit Top 200 Rows": you can edit data right away!
  2. Remember to add SET DATEFORMAT YMD before the INSERT command.

Via https://stackoverflow.com/a/51186767/14507440