Artemination
Artemination

Reputation: 723

How to format a SQL query from a table column?

I store some SQL queries in a table, in a varchar column. Then I execute them in my Birts Reports Data Sets, that's ok, but sometimes I need to check the SQL query but when I copy from the SQL editor then I get the query in a single line.. I would like to know how to get that column and give some indentation, like before it was inserted into the table.

Upvotes: 0

Views: 192

Answers (3)

Devart
Devart

Reputation: 121932

Try our free on-line tool - SQL Formatter

Upvotes: 1

Artemination
Artemination

Reputation: 723

I found this sp at T-SQL_Exceeding_the_8000_Byte_Limit_of_the_PRINT_Statement

-- Works around the 4000/8000 character limit of the print statement
CREATE PROCEDURE dbo.LongPrint( @string nvarchar(max) )
AS
SET NOCOUNT ON

set @string = rtrim( @string )

declare @cr char(1), @lf char(1)
set @cr = char(13)
set @lf = char(10)

declare @len int, @cr_index int, @lf_index int, @crlf_index int, @has_cr_and_lf bit, @left nvarchar(4000), @reverse nvarchar(4000)
set @len = 4000

while ( len( @string ) > @len )
begin
   set @left = left( @string, @len )
   set @reverse = reverse( @left )
   set @cr_index = @len - charindex( @cr, @reverse ) + 1
   set @lf_index = @len - charindex( @lf, @reverse ) + 1
   set @crlf_index = case when @cr_index < @lf_index then @cr_index else @lf_index end
   set @has_cr_and_lf = case when @cr_index < @len and @lf_index < @len then 1 else 0 end
   print left( @string, @crlf_index - 1 )
   set @string = right( @string, len( @string ) - @crlf_index - @has_cr_and_lf )
end

print @string

It functions very well..

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85056

I've used this tool in the past and it works pretty well:

http://www.dpriver.com/pp/sqlformat.htm

Upvotes: 1

Related Questions