views:

20

answers:

3

I have a SQL script that acquires table names and creates trigger for those tables. When I open the trigger after creating it all of the code is on one line. How would I go about adding tab and new line characters within the script to make the trigger more readable.

Example code:

SET @SQL = 'ALTER TRIGGER [dbo].[TRG_' + SUBSTRING(@TABLE_NAME,5, LEN(@TABLE_NAME)) + '_$AUD] '
        SET @SQL = @SQL + 'ON [dbo].[' + @TABLE_NAME + '] '
        SET @SQL = @SQL + 'FOR UPDATE, DELETE '
        SET @SQL = @SQL + 'AS '
        SET @SQL = @SQL + 'DECLARE '
        SET @SQL = @SQL + '@BIT INT, '
        SET @SQL = @SQL + '@FIELD INT, '
        SET @SQL = @SQL + '@CHAR INT '
A: 

This won't change the actual trigger definition, but you could use a tool like Instant SQL Formatter, when you need to work on it.

JohnFx
Im going to keep that link handy for other instances, I have way too many triggers to change as of this moment. But thank you though, it does work awesome, just tried it
mattgcon
+1  A: 

For MS SQL at least, you can either use CHAR() with the correct ASCII values and concatenate at the correct places in your strings, or you can just include the newlines, tabs, etc. within your SQL strings themselves. The string can span multiple lines. For example, this should work:

SET @SQL = 'ALTER TRIGGER [dbo].[TRG_' + SUBSTRING(@TABLE_NAME,5, LEN(@TABLE_NAME)) + '_$AUD]
ON [dbo].[' + @TABLE_NAME + ']
...

'
Tom H.
This worked beautifully. Question answered
mattgcon
A: 

use this

SET @SQL = 'ALTER TRIGGER [dbo].[TRG_' + SUBSTRING(@TABLE_NAME,5, LEN(@TABLE_NAME)) + '_$AUD] 
        ON [dbo].[' + @TABLE_NAME + '] 
        FOR UPDATE, DELETE 
        AS 
        DECLARE 
        @BIT INT, 
        @FIELD INT, 
        @CHAR INT '
Madhivanan