03 May 2023

SQL - Shrink all user databases

USE MASTER
GO

CREATE OR ALTER PROCEDURE Boso_ShrinkAllUserDB_sp
(
    @DBName AS sysname = NULL
)
AS
BEGIN
    --##2023-15-24 - Boso -             @DBName
    SET NOCOUNT ON

    DECLARE @SQ NVARCHAR(MAX)

    DECLARE #CUR CURSOR FOR
    SELECT  CONCAT('; PRINT ''** ', NAME ,' '' ; DBCC SHRINKDATABASE(', QUOTENAME(NAME) ,')') AS COMANDO
    FROM    SYS.DATABASES
    WHERE   STATE = 0           --> ONLINE DB ONLY
        AND DATABASE_ID > 4     --> SKIP SYSTEM DBS
        AND (@DBName IS NULL OR name = @DBName)


    OPEN #CUR
    FETCH NEXT FROM #CUR INTO @SQ

    WHILE @@FETCH_STATUS = 0
        BEGIN
            EXEC SP_EXECUTESQL @SQ

            FETCH NEXT FROM #CUR INTO @SQ
        END


    CLOSE #CUR
    DEALLOCATE #CUR

END
GO

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