How can we help you today? How can we help you today?

How to apply SQL Prompt code formatting and style outside SSMS

I have a SQL process which dynamically creates new stored procedures and I am looking for a way to apply the SQL Prompt Formatting and Styles to it before actually creating the new procedure in the database. Any ideas? 

I am using SQL Prompt 11.1.3.18786

Patrick Ortuso
0

Comments

3 comments

  • Jon Kirkwood
    Official comment

    Hi Patrick Ortuso 

    Thank you for reaching out via the Redgate forums regarding your SQL Prompt formatting inquiry. 

    You could potentially do this using the SQL Prompt bulk-formatter formatter, which lets you apply formatting styles to SQL inside or outside of SSMS before it’s executed. 

    This is the supported way to format dynamically generated SQL, as there’s no API or T-SQL function to apply SQL Prompt styles directly in memory. 

     

    How it could work in your case: 

    1. Your process generates the stored procedure SQL
    2. Write it out to a .sql file
    3. Run the SQL Prompt command-line formatter on that file 
    4. Alternatively run the bulk-formatter from within SSMS
    5. It rewrites the file using your chosen SQL Prompt style
    6. Execute the formatted SQL to create the procedure 

    Licensing note: The bulk formatting / command-line operations requires either a SQL Toolbelt Essentials or SQL Toolbelt license. It’s not included with standalone SQL Prompt. 

     

    Here are some documentation links if you would like to learn more about this:

    Within SSMS: https://documentation.red-gate.com/sp/features-requiring-a-specific-license/bulk-operations/bulk-operations-in-ssms/bulk-formatting  

    Via Command-Line: https://documentation.red-gate.com/sp/features-requiring-a-specific-license/bulk-operations/bulk-operations-via-the-command-line 

    Jon Kirkwood
  • Patrick Ortuso

    ok, thanks. I will try it

     

    Patrick Ortuso
    0
  • timothyeithan

    If you can’t directly use SQL Prompt’s API, consider creating a temporary table to hold the SQL code, format it manually, and then execute it: 

    DECLARE @sql NVARCHAR(MAX);

    -- Dynamically create your SQL statement
    SET @sql = '
    CREATE PROCEDURE dbo.MyNewProcedure
    AS
    BEGIN
       SELECT * FROM MyTable;
    END
    ';

    -- Store it in a temp table for formatting (if applicable)
    CREATE TABLE #TempSQL (SQLCode NVARCHAR(MAX));
    INSERT INTO #TempSQL (SQLCode) VALUES (@sql);

    -- Format manually or use SQL Prompt if applicable
    -- (You may need to copy this for manual formatting)

    -- Execute the formatted SQL
    EXEC sp_executesql (SELECT SQLCode FROM #TempSQL);
    DROP TABLE #TempSQL;
     

    timothyeithan
    0

Add comment

Please sign in to leave a comment.