I have log files that contain SQL statements in the following format:
exec sp_executeSQL @stmt=N'SELECT Field1, Field2, Field3 FROM MyTable WHERE Field1 = @P1 AND Field2 = @P2', @params=N'@P1 Numeric(15,3), @P2 varchar(20)', @P1='1234.54', @P2='Hello'
I’d like to format it like this:
SELECT Field1, Field2, Field3
FROM MyTable
WHERE Field1 = 1234.54
AND Field2 = 'Hello'
Parsing the message manually (i.e. stripping out the statement and replacing @P1, @P2 with their corresponding values is possible, but you’d need to deal with all the different types)
I’m looking for something that is the reverse of GetCommandLogString mentioned here
I ended up using the TSql100Parser available in Microsoft.Data.Schema.ScriptDom.
Essentially, it will parse a SQL query, and in the case of the query I had in my question, return a ‘ExecuteStatement’ broken down into it’s various parts (Statement, variables, variable values etc). I then manipulate this, and use the Sql100ScriptGenerator to format the resulting SQL statement into something human readable.