Question

I am trying to pull the input buffer data (DBCC INPUTBUFFER(@SPID)) for each record returned for a database when querying the SYSPROCESSES table. I am interested to hear if there is a better way to accomplish this, but would also appreciate correction to what I currently have working for learning purposes.

DECLARE @Max [int]
DECLARE @Min [int] = 1

SELECT @Max = COUNT(SPID)
FROM MASTER.DBO.SYSPROCESSES
WHERE DB_NAME(DBID) = 'Northwinds' AND DBID != 0

CREATE TABLE #Results (
    EventType [nvarchar](1024),
    Parameters [int],
    EventInfo [nvarchar](1024),
    SPID [int],
    STATUS [nvarchar](255),
    PROGRAM_NAME [nvarchar](1024),
    CMD [nvarchar](255),
    LOGINAME [nvarchar](255)
)

WHILE @Min <= @Max
BEGIN

    DECLARE @SPID [int]

    WITH SelectedRow AS (
        SELECT SPID, ROW_NUMBER() OVER (ORDER BY SPID) AS RowNumber
        FROM MASTER.DBO.SYSPROCESSES
        WHERE DB_NAME(DBID) = 'Northwinds' AND DBID != 0
    )

    SELECT @SPID = SPID
    FROM SelectedRow
    WHERE RowNumber = @Min

    DECLARE @InputBuffer TABLE (
        EventType [nvarchar](1024),
        Parameter [int],
        EventInfo [nvarchar](1024)
    )

    DECLARE @SysProcesses TABLE (
        SPID [int],
        STATUS [nvarchar](255),
        PROGRAM_NAME [nvarchar](1024),
        CMD [nvarchar](255),
        LOGINAME [nvarchar](255)
    )

    INSERT @InputBuffer 
        EXEC('DBCC INPUTBUFFER('+@SPID+')')

    INSERT @SysProcesses 
        SELECT SPID, STATUS, PROGRAM_NAME, CMD, LOGINAME
        FROM MASTER.DBO.SYSPROCESSES
        WHERE DB_NAME(DBID) = 'Northwinds' AND DBID != 0 AND SPID = @SPID

    INSERT INTO #TempResults(EventType, Parameters, EventInfo, SPID, STATUS, PROGRAM_NAME, CMD, LOGINAME)
        SELECT *
        FROM @InputBuffer, @SysProcesses

    SET @Min = (@Min + 1)
END

Now when I execute the following query:

SELECT SPID
FROM MASTER.DBO.SYSPROCESSES
WHERE DB_NAME(DBID) = 'Northwinds' AND DBID != 0

it returns 31 rows...

However when I SELECT * FROM #TempResults after executing the above loop I am returning mass amounts of duplicates in the temp table...to the sum of 10751.

Again this is mostly for learning, but would be a pretty handy function to have as well. I am looking for information on what I'm missing causing the duplicate records to be returned, as well as a possible better solution.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top