How to generate scripts from the SSMS results grid
Last modified: August 5, 2024
It is easy to generate scripts from the results grid based on the required table data with the following statements: INSERT, INSERT #tmpTable, WHERE IN(), WHERE AND OR, and UPDATE.
Let’s take the following query as an example:
USE AdventureWorks2019
GO
SELECT ProductID, ProductNumber,Color, ReorderPoint, ListPrice
FROM Production.Product
WHERE Color IS NOT NULL AND ListPrice != 0
To generate a script with the required statement:
1. In the results grid, select the cells for which you want to generate a script.
2. Right-click the selected cells and select Generate Script As > statement type and then choose whether the output should be opened in a new window, copied to the clipboard, or saved to a file.
Alternatively, select the cells and generate the script to the clipboard by using the appropriate shortcut depending on the statement type:
- Ctrl+J,I for the INSERT statement
- Ctrl+J,T for the INSERT#tmpTable statement
- Ctrl+J,W for the WHERE IN() statement
- Ctrl+J,O for the WHERE AND OR statement
- Ctrl+J,U for the UPDATE statement
Now, if we generate scripts with every statement type using the same selected data, we will get the following:
INSERT statement
SET DATEFORMAT ymd
INSERT INTO [Table] (ProductNumber) VALUES
(N'FR-R92B-58'),
(N'FR-R92R-58'),
(N'HL-U509-R'),
(N'HL-U509')
GO
INSERT #tmpTable statement
SET DATEFORMAT ymd
CREATE TABLE #tmpTable (
ProductNumber nvarchar(25))
INSERT INTO #tmpTable (ProductNumber) VALUES
(N'FR-R92B-58'),
(N'FR-R92R-58'),
(N'HL-U509-R'),
(N'HL-U509')
GO
SELECT * FROM #tmpTable
DROP TABLE #tmpTable
GO
WHERE IN() statement
WHERE ProductNumber IN(N'FR-R92B-58', N'FR-R92R-58', N'HL-U509-R', N'HL-U509')
WHERE AND OR statement
WHERE (ProductNumber = N'FR-R92B-58') OR
(ProductNumber = N'FR-R92R-58') OR
(ProductNumber = N'HL-U509-R') OR
(ProductNumber = N'HL-U509')
UPDATE statement
SET DATEFORMAT ymd
UPDATE [Table] SET ProductNumber = N'FR-R92B-58' WHERE ProductID = 680
GO
UPDATE [Table] SET ProductNumber = N'FR-R92R-58' WHERE ProductID = 706
GO
UPDATE [Table] SET ProductNumber = N'HL-U509-R' WHERE ProductID = 707
GO
UPDATE [Table] SET ProductNumber = N'HL-U509' WHERE ProductID = 708
GO