2

I am trying to write an output of SQL Agent Job to the text or excel or CSV file.

But it's writing all over it's making it very huge file with white spaces and line like '-------'see below pic. I tried trimming, removing special characters.

Here is my job.

Select data.BlockingSessionID,data.VictimSessionID,LTRIM(RTRIM(data.BlockingQuery)),LTRIM(RTRIM(data.VictimQuery)),data.WaitDurationSecond,data.WaitType,data.BlockingQueryCompletePercent

from(
SELECT
     blocking_session_id AS BlockingSessionID,
     session_id AS VictimSessionID,

     (SELECT [text] FROM sys.sysprocesses
      CROSS APPLY sys.dm_exec_sql_text([sql_handle])
      WHERE spid = blocking_session_id) AS BlockingQuery,

     [text] AS VictimQuery,
     wait_time/1000 AS WaitDurationSecond,
     wait_type AS WaitType,
     percent_complete AS BlockingQueryCompletePercent
FROM sys.dm_exec_requests
CROSS APPLY sys.dm_exec_sql_text([sql_handle])
WHERE blocking_session_id > 0) data

and here is the screen shots or the file where whole Victim and Blocking query get separated by spaces.

Here are some screen shots as how it looks like when it writes to file.This is the result when lock happens, i would like to write this to text file but it writes with thousands of white spaces. See below pic.

enter image description here

Actual Text file, enter image description here

enter image description here

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
user2040021
  • 309
  • 3
  • 15

1 Answers1

2

Manually format your output as a single string to avoid this. For example:

Select cast(data.BlockingSessionID as varchar(max)) + '||' + 
    cast(data.VictimSessionID as varchar(max) + '||' + 
    LTRIM(RTRIM(data.BlockingQuery)) + '||' + 
    LTRIM(RTRIM(data.VictimQuery)) + '||' + 
    CAST(data.WaitDurationSecond as varchar(max)) + '||' + 
    data.WaitType + '||' +
    Cast(data.BlockingQueryCompletePercent as varchar(max))
from(
SELECT
     blocking_session_id AS BlockingSessionID,
     session_id AS VictimSessionID,




     (SELECT [text] FROM sys.sysprocesses
      CROSS APPLY sys.dm_exec_sql_text([sql_handle])
      WHERE spid = blocking_session_id) AS BlockingQuery,

     [text] AS VictimQuery,
     wait_time/1000 AS WaitDurationSecond,
     wait_type AS WaitType,
     percent_complete AS BlockingQueryCompletePercent
FROM sys.dm_exec_requests
CROSS APPLY sys.dm_exec_sql_text([sql_handle])
WHERE blocking_session_id > 0) data
Laughing Vergil
  • 3,706
  • 1
  • 14
  • 28
  • Thanks @laughing Vergil for this, it does everything in one line now but still have those -------------------------------------- and white spaces and they are a lot. I guess I can work with this for now, until we figure out how to take care of above "------" and "white Spaces" – user2040021 Dec 13 '16 at 17:40
  • Actually it worked out perfectly when I write into SQL File. Thanks again. – user2040021 Dec 13 '16 at 17:42