/************************************************************************************************/
/** Drop all _cvp objects                                                                      **/
/************************************************************************************************/
DECLARE @lorsData CURSOR, @lcNAME NVARCHAR(128), @lcTYPE NVARCHAR(128), @lcSQL NVARCHAR(4000)
SET @lorsData=CURSOR LOCAL READ_ONLY FOR
    SELECT AB.Name+'.'+AA.NAME, AA.TYPE
      FROM SYS.ALL_OBJECTS AA INNER JOIN sys.schemas AB ON AA.schema_ID=AB.schema_ID
      WHERE AA.NAME LIKE '[_]CVP[_]%'

OPEN @lorsData
WHILE 0 = 0 BEGIN
  FETCH NEXT FROM @lorsData INTO @lcNAME, @lcTYPE
  IF @@FETCH_STATUS <> 0 BREAK
 
  SET @lcSQL='DROP '+CASE WHEN @lcTYPE='P' THEN 'PROCEDURE' ELSE 'FUNCTION' END+' '+@lcNAME
  EXEC (@lcSQL)
END
CLOSE @lorsData
DEALLOCATE @lorsData
GO

IF NOT OBJECT_ID('dbo._CVP_CHECKGRANT') IS NULL DROP PROCEDURE dbo._CVP_CHECKGRANT
GO
CREATE PROCEDURE dbo._CVP_CHECKGRANT
AS
BEGIN
 DECLARE @lorsData CURSOR
 DECLARE @lcNAME NVARCHAR(128), @liEXISTS INT, @lcLIST NVARCHAR(MAX)

 PRINT 'bulk admin role: '+ CASE WHEN IS_SRVROLEMEMBER('bulkadmin')=1 THEN 'Yes' ELSE 'No' END

 IF ISNULL(HAS_DBACCESS('master'),0)=0 BEGIN
    SET @lcLIST='/*****************************************/'+CHAR(10)+
                '/** RUN this                            **/'+CHAR(10)+
                '/*****************************************/'+CHAR(10)+
                REPLACE('USE master; CREATE USER [%LOGIN%] FOR LOGIN [%LOGIN%];'+CHAR(10)+'GO'+CHAR(10),'%LOGIN%',SYSTEM_USER)
    PRINT @lcLIST
    END
 ELSE BEGIN
    PRINT REPLACE('USER %LOGIN% has access to database master', '%LOGIN%',SYSTEM_USER)
 END

 IF (SELECT COUNT(1) FROM fn_my_permissions(NULL, 'server') WHERE permission_name='ALTER TRACE')=0 BEGIN
    SET @lcLIST='/*****************************************/'+CHAR(10)+
                '/** RUN this                            **/'+CHAR(10)+
                '/*****************************************/'+CHAR(10)+
                REPLACE('GRANT ALTER TRACE TO [%LOGIN%];'+CHAR(10)+'GO'+CHAR(10),'%LOGIN%',SYSTEM_USER)
    PRINT @lcLIST
    END
 ELSE BEGIN
    PRINT REPLACE('USER %LOGIN% has "ALTER TRACE permissions"', '%LOGIN%',SYSTEM_USER)
 END

 IF (SELECT SUM(CASE WHEN VALUE=1 THEN 1 ELSE 0 END) FROM sys.configurations WHERe NAME IN ('show advanced options','Ole Automation Procedures'))<2 BEGIN
    SET @lcLIST='/*****************************************/'+CHAR(10)+
                '/** RUN this                            **/'+CHAR(10)+
                '/*****************************************/'+CHAR(10)+
                'sp_configure ''show advanced options'', 1;'+CHAR(10)+
                'GO'+CHAR(10)+
                'RECONFIGURE; '+CHAR(10)+
                'GO'+CHAR(10)+
                'sp_configure ''Ole Automation Procedures'', 1;'+CHAR(10)+
                'GO'+CHAR(10)+
                'RECONFIGURE; '+CHAR(10)+
                'GO'+CHAR(10)

    PRINT @lcLIST
    END
 ELSE BEGIN
    PRINT 'Server has "Ole Automation Procedures" set to 1'
 END

 SET @lcLIST=''
 SET @lorsData=CURSOR LOCAL READ_ONLY FOR
  SELECT BA.name, ISNULL(BB.ISEXISTS,0)
    FROM (SELECT 'sp_OACreate' AS NAME
          UNION 
          SELECT 'sp_OADestroy'
          UNION 
          SELECT 'sp_OAGetErrorInfo'
          UNION 
          SELECT 'sp_OAMethod') BA LEFT JOIN (SELECT AB.name, CASE WHEN AA.permission_name='EXECUTE' THEN 1 ELSE 0 END AS ISEXISTS
                                                FROM master.sys.database_permissions AA JOIN sys.system_objects AB ON AA.major_id = AB.object_id
                                                WHERE AA.class = 1 AND AB.parent_object_id = 0 AND AB.name IN ('sp_OACreate','sp_OADestroy','sp_OAGetErrorInfo','sp_OAMethod')
                                              ) BB ON BA.NAME=BB.NAME
 OPEN @lorsData
 WHILE 0 = 0 BEGIN
   FETCH NEXT FROM @lorsData INTO @lcNAME, @liEXISTS
   IF @@FETCH_STATUS <> 0 BREAK

   PRINT @lcNAME+' '+CASE WHEN @liEXISTS=1 THEN 'GRANTED' ELSE 'NONGRANTED' END
 
   IF @liEXISTS=0 BEGIN
      SET @lcLIST=@lcLIST+'GRANT EXEC ON '+@lcNAME+' TO ['+SYSTEM_USER+']'+CHAR(10)+'GO'+CHAR(10)
   END
   
 END
 CLOSE @lorsData
 DEALLOCATE @lorsData

 IF LEN(@lcLIST)>0 BEGIN
    PRINT ''
    PRINT 'Missing grant of procedure'
    PRINT '/*****************************************/'+CHAR(10)+
          '/** RUN this                            **/'+CHAR(10)+
          '/*****************************************/'+CHAR(10)+
          'use master'+CHAR(10)+
		  @lcLIST
    PRINT ''
 END



END --_CVP_CHECKGRANT
GO

--exec dbo._CVP_CHECKGRANT


IF NOT OBJECT_ID('dbo._CVP_SAVESRCS') IS NULL DROP PROCEDURE dbo._CVP_SAVESRCS
GO
CREATE PROCEDURE dbo._CVP_SAVESRCS(@lcFOLDER NVARCHAR(1000), @lcSHORTFILENAME NVARCHAR(1000), @liMODE INT=1)
AS
BEGIN
 DECLARE @lorsData CURSOR, @lorsDB CURSOR
 DECLARE @liErr INT, @liErrX INT, @loFSO INT, @loTXT INT, @lcMSG VARCHAR(MAX), @liFLAG INT, @lcFile VARCHAR(2000),
         @lcLINE VARCHAR(MAX), @liS BIGINT, @liDATABASEID INT, @lcNAME NVARCHAR(256), @liID INT, @lcBUFFERP VARCHAR(MAX),
         @loLOGIF INT, @loLOGIP INT, @loLOGIS INT, @lcLOGIF VARCHAR(2000), @lcLOGIP VARCHAR(2000), @lcLOGIS VARCHAR(2000),
         @liDBID INT, @liPID INT, @liOBJECTID INT, @lnDURATION_SUM NUMERIC(20,6), @liRUNS BIGINT

 DECLARE @lcFILENAME VARCHAR(100), @lcTEXT NVARCHAR(MAX), @liTLEN BIGINT

BEGIN TRY

 EXECUTE @liErr = sp_OACreate  'Scripting.FileSystemObject' , @loFSO OUT

 IF @liErr<>0 GOTO _CVP_SAVESRCS_END

 SET @lcFOLDER=@lcFOLDER+CASE WHEN RIGHT(@lcFOLDER,1)<>'\' THEN '\' ELSE '' END

 -- vytvoření statistického souboru
 SET @lcLOGIS=@lcFOLDER+@lcSHORTFILENAME+'.logis'
 EXECUTE @liErr = sp_OACreate  'ADODB.Stream' , @loLOGIS OUT
 EXECUTE @liErr = sp_OASetProperty  @loLOGIS, 'Mode', 3 --Read/Write
 EXECUTE @liErr = sp_OASetProperty  @loLOGIS, 'Type', 2 --text
 EXECUTE @liErr = sp_OASetProperty  @loLOGIS, 'Charset', 'Windows-1250'
 EXECUTE @liErr = sp_OAMethod  @loLOGIS, 'Open', Null

 SET @lcLINE=(SELECT CAST(DATABASEIDLEN AS VARCHAR(30))+','+CAST(OBJECTIDLEN AS VARCHAR(30))+','+CAST(NESTLEVELLEN AS VARCHAR(30)) FROM #STATS)

 EXECUTE @liErr = sp_OAMethod  @loLOGIS, 'WriteText', NULL, @lcLINE

 EXECUTE @liErr = sp_OAMethod  @loLOGIS, 'SaveToFile', NULL, @lcLOGIS, 2
 EXECUTE sp_OAMethod  @loLOGIS, 'Close', NULL
 EXECUTE sp_OADestroy @loLOGIS
 IF @liErr=0 BEGIN
    SET @lcMSG=REPLACE('Export dat do souboru %FILE%.','%FILE%',@lcLOGIS)
    PRINT @lcMSG
 END
 
 _CVP_SAVESRCS_TXT:

 IF @liMODE=2 BEGIN
    SET @lcLOGIF=@lcFOLDER+@lcSHORTFILENAME+'.logif'
    SET @lcLOGIP=@lcFOLDER+@lcSHORTFILENAME+'.logip'

    -- vytvoření textového souboru
    EXECUTE @liErr = sp_OACreate  'ADODB.Stream' , @loLOGIF OUT
    EXECUTE @liErr = sp_OASetProperty  @loLOGIF, 'Mode', 3 --Read/Write
    EXECUTE @liErr = sp_OASetProperty  @loLOGIF, 'Type', 2 --text
    EXECUTE @liErr = sp_OASetProperty  @loLOGIF, 'Charset', 'Windows-1250'
    EXECUTE @liErr = sp_OAMethod  @loLOGIF, 'Open', Null
    IF @liErr<>0 BEGIN 
       SET @lcMSG=REPLACE('Nelze vytvořit soubor %FILE%. Export zrušen.','%FILE%',@lcLOGIF)
       PRINT @lcMSG
       GOTO _CVP_SAVESRCS_END
    END 

    -- vytvoření textového souboru
    EXECUTE @liErr = sp_OACreate  'ADODB.Stream' , @loLOGIP OUT
    EXECUTE @liErr = sp_OASetProperty  @loLOGIP, 'Mode', 3 --Read/Write
    EXECUTE @liErr = sp_OASetProperty  @loLOGIP, 'Type', 2 --text
    EXECUTE @liErr = sp_OASetProperty  @loLOGIP, 'Charset', 'Windows-1250'
    EXECUTE @liErr = sp_OAMethod  @loLOGIP, 'Open', Null
    IF @liErr<>0 BEGIN 
       SET @lcMSG=REPLACE('Nelze vytvořit soubor %FILE%. Export zrušen.','%FILE%',@lcLOGIP)
       PRINT @lcMSG
       GOTO _CVP_SAVESRCS_END
    END 
 END

 SET @lorsDB=CURSOR LOCAL READ_ONLY FOR
   SELECT ID, DATABASEID, FILENAME
     FROM #DBs
     WHERE DATABASEID IN (SELECT DATABASEID FROM #OBJECTs)
 

 OPEN @lorsDB
 WHILE 0 = 0 BEGIN
   FETCH NEXT FROM @lorsDB INTO @liDBID, @liDATABASEID, @lcFILENAME
   IF @@FETCH_STATUS <> 0 BREAK

   SET @lcFile=@lcFOLDER+@lcFILENAME

   IF @liMODE=2 BEGIN
      SET @lcLINE=CAST(@liDBID AS VARCHAR(30))+','+@lcFILENAME+','+CAST(@liDATABASEID AS VARCHAR(30))+CHAR(13)+CHAR(10)
      EXECUTE @liErr = sp_OAMethod  @loLOGIF, 'WriteText', NULL, @lcLINE
   END

   -- vytvoření textového souboru
   EXECUTE @liErr = sp_OACreate  'ADODB.Stream' , @loTXT OUT
   EXECUTE @liErr = sp_OASetProperty  @loTXT, 'Mode', 3 --Read/Write
   EXECUTE @liErr = sp_OASetProperty  @loTXT, 'Type', 2 --text
   EXECUTE @liErr = sp_OASetProperty  @loTXT, 'Charset', 'Windows-1250'
   EXECUTE @liErr = sp_OAMethod  @loTXT, 'Open', Null
   IF @liErr<>0 BEGIN 
      SET @lcMSG=REPLACE('Nelze vytvořit soubor %FILE%. Export zrušen.','%FILE%',@lcFile)
      PRINT @lcMSG
      BREAK
   END 

   SET @lcBUFFERP=''


   SET @lorsData=CURSOR LOCAL READ_ONLY FOR
     SELECT SOURCE, LEN('a'+SOURCE+'a')-2 AS TLEN, 
            CAST(@liDBID AS VARCHAR(30))+','+CAST(ID AS VARCHAR(30))+',,'+OWNER+'.'+NAME+','+CAST(OBJECTID AS VARCHAR(30))+','+
            CAST(COALESCE(DURATION_SUM,0) AS VARCHAR(30))+','+CAST(RUNS AS VARCHAR(30))+CHAR(13)+CHAR(10)
       FROM #OBJECTs 
       WHERE DATABASEID=@liDATABASEID
       ORDER BY ID

  OPEN @lorsData
   WHILE 0 = 0 BEGIN
     FETCH NEXT FROM @lorsData INTO @lcTEXT, @liTLEN, @lcBUFFERP
     IF @@FETCH_STATUS <> 0 BREAK

     --PRINT @lcNAME

     IF @liMODE=2 BEGIN
        EXECUTE @liErr = sp_OAMethod  @loLOGIP, 'WriteText', NULL, @lcBUFFERP
        --IF @liErr<>0 BEGIN PRINT 'BEM''s ATTACK' BREAK END
     END

 --DECLARE @output varchar(255), @source varchar(255), @description varchar(255), @hr int
 --EXEC @hr = sp_OAGetErrorInfo @loTXT, @source OUT, @description OUT
 --IF @hr = 0 BEGIN
 --   PRINT 'OLE Automation Error Information'
 --   PRINT '  Source: ' + @source
 --   PRINT '  Description: ' + @description
 --END

     SET @lcTEXT=@lcTEXT+CHAR(13)+CHAR(10)
     EXECUTE @liErr = sp_OAMethod  @loTXT, 'WriteText', NULL, @lcTEXT


   END
   CLOSE @lorsData
   DEALLOCATE @lorsData

   --EXECUTE @liErr = sp_OAMethod  @loLOGIP, 'WriteText', NULL, @lcBUFFERP
   --IF @liErr<>0 BEGIN PRINT 'BEM''s ATTACK' BREAK END
 


   EXECUTE @liErr = sp_OAMethod  @loTXT, 'SaveToFile', NULL, @lcFile, 2
   -- zavři výstupní soubor
   EXECUTE @liErrX = sp_OAMethod  @loTXT, 'Close'
   SET @liErr=@liErr|@liErrX
   EXECUTE sp_OADestroy @loTXT

   IF @liErr=0 BEGIN
      SET @lcMSG=REPLACE('Export dat do souboru %FILE%.','%FILE%',@lcFile)
      PRINT @lcMSG
   END

   IF @liErr<>0 BEGIN
      SET @lcMSG=REPLACE('Nelze vytvořit soubor %FILE%. Export zrušen.','%FILE%',@lcFile)
      PRINT @lcMSG
   END


 END
 CLOSE @lorsDB
 DEALLOCATE @lorsDB


 IF @liMODE=2 BEGIN
    EXECUTE @liErr = sp_OAMethod  @loLOGIF, 'SaveToFile', NULL, @lcLOGIF, 2
    EXECUTE sp_OAMethod  @loLOGIF, 'Close', Null
    EXECUTE sp_OADestroy @loLOGIF

    IF @liErr=0 BEGIN
       SET @lcMSG=REPLACE('Export dat do souboru %FILE%.','%FILE%',@lcLOGIF)
       PRINT @lcMSG
    END
    IF @liErr<>0 BEGIN
       SET @lcMSG=REPLACE('Nelze vytvořit soubor %FILE%. Export zrušen.','%FILE%',@lcLOGIF)
       PRINT @lcMSG
    END

    EXECUTE @liErr = sp_OAMethod  @loLOGIP, 'SaveToFile', NULL, @lcLOGIP, 2
    EXECUTE sp_OAMethod  @loLOGIP, 'Close', Null
    EXECUTE sp_OADestroy @loLOGIP

    IF @liErr=0 BEGIN
       SET @lcMSG=REPLACE('Export dat do souboru %FILE%.','%FILE%',@lcLOGIP)
       PRINT @lcMSG
    END
    IF @liErr<>0 BEGIN
       SET @lcMSG=REPLACE('Nelze vytvořit soubor %FILE%. Export zrušen.','%FILE%',@lcLOGIP)
       PRINT @lcMSG
    END

 END
 --END IF @liMODE=2



 _CVP_SAVESRCS_END:
 EXECUTE sp_OADestroy @loFSO

END TRY

BEGIN CATCH
 SET @lcMSG=CAST(ERROR_PROCEDURE() AS VARCHAR(30))+' '+CAST(ERROR_NUMBER() AS VARCHAR(30))+' '+ERROR_MESSAGE()
 PRINT '***********************************************************'
 PRINT @lcMSG
 PRINT '***********************************************************'
END CATCH

END --_CVP_SAVESRCS
GO



IF NOT OBJECT_ID('dbo._CVP_CRC32') IS NULL DROP PROCEDURE dbo._CVP_CRC32
GO
CREATE PROCEDURE dbo._CVP_CRC32 (@input VARCHAR(MAX), @lcCRC32 VARCHAR(10) OUT)  
AS  
BEGIN 
 DECLARE @crc BIGINT, @len INT, @i INT, @index INT, @tblval BIGINT, @lcRet CHAR(10)

 SELECT @crc = 0xFFFFFFFF, @len = LEN(@input), @i = 1

 WHILE @i <= @len BEGIN
   SET @index = ((@crc & 0xff) ^ ASCII(SUBSTRING(@input, @i, 1)))      
   SET @tblval = (SELECT Value FROM #_CVP_CRC32 WHERE ID = @Index)
   SET @crc = (@crc / 256) ^ @tblval   
   SET @i = @i + 1     
 END
 SET @crc = ~@crc

 --SELECT @crc+0xFFFFFFFF+1 as CRC32, CONVERT(VARBINARY(4), @crc) as CRC32Hex
 --SELECT @lcRet=@crc+0xFFFFFFFF+1

 SET @lcCRC32=@crc+0xFFFFFFFF+1
END --_CVP_CRC32
GO

IF NOT OBJECT_ID('dbo._CVP_FILLCRC32') IS NULL DROP PROCEDURE dbo._CVP_FILLCRC32
GO
CREATE PROCEDURE dbo._CVP_FILLCRC32 
AS  
BEGIN
 INSERT INTO #_CVP_CRC32 VALUES (0)
 INSERT INTO #_CVP_CRC32 VALUES (1996959894)
 INSERT INTO #_CVP_CRC32 VALUES (3993919788)
 INSERT INTO #_CVP_CRC32 VALUES (2567524794)
 INSERT INTO #_CVP_CRC32 VALUES (124634137)
 INSERT INTO #_CVP_CRC32 VALUES (1886057615)
 INSERT INTO #_CVP_CRC32 VALUES (3915621685)
 INSERT INTO #_CVP_CRC32 VALUES (2657392035)
 INSERT INTO #_CVP_CRC32 VALUES (249268274)
 INSERT INTO #_CVP_CRC32 VALUES (2044508324)
 INSERT INTO #_CVP_CRC32 VALUES (3772115230)
 INSERT INTO #_CVP_CRC32 VALUES (2547177864)
 INSERT INTO #_CVP_CRC32 VALUES (162941995)
 INSERT INTO #_CVP_CRC32 VALUES (2125561021)
 INSERT INTO #_CVP_CRC32 VALUES (3887607047)
 INSERT INTO #_CVP_CRC32 VALUES (2428444049)
 INSERT INTO #_CVP_CRC32 VALUES (498536548)
 INSERT INTO #_CVP_CRC32 VALUES (1789927666)
 INSERT INTO #_CVP_CRC32 VALUES (4089016648)
 INSERT INTO #_CVP_CRC32 VALUES (2227061214)
 INSERT INTO #_CVP_CRC32 VALUES (450548861)
 INSERT INTO #_CVP_CRC32 VALUES (1843258603)
 INSERT INTO #_CVP_CRC32 VALUES (4107580753)
 INSERT INTO #_CVP_CRC32 VALUES (2211677639)
 INSERT INTO #_CVP_CRC32 VALUES (325883990)
 INSERT INTO #_CVP_CRC32 VALUES (1684777152)
 INSERT INTO #_CVP_CRC32 VALUES (4251122042)
 INSERT INTO #_CVP_CRC32 VALUES (2321926636)
 INSERT INTO #_CVP_CRC32 VALUES (335633487)
 INSERT INTO #_CVP_CRC32 VALUES (1661365465)
 INSERT INTO #_CVP_CRC32 VALUES (4195302755)
 INSERT INTO #_CVP_CRC32 VALUES (2366115317)
 INSERT INTO #_CVP_CRC32 VALUES (997073096)
 INSERT INTO #_CVP_CRC32 VALUES (1281953886)
 INSERT INTO #_CVP_CRC32 VALUES (3579855332)
 INSERT INTO #_CVP_CRC32 VALUES (2724688242)
 INSERT INTO #_CVP_CRC32 VALUES (1006888145)
 INSERT INTO #_CVP_CRC32 VALUES (1258607687)
 INSERT INTO #_CVP_CRC32 VALUES (3524101629)
 INSERT INTO #_CVP_CRC32 VALUES (2768942443)
 INSERT INTO #_CVP_CRC32 VALUES (901097722)
 INSERT INTO #_CVP_CRC32 VALUES (1119000684)
 INSERT INTO #_CVP_CRC32 VALUES (3686517206)
 INSERT INTO #_CVP_CRC32 VALUES (2898065728)
 INSERT INTO #_CVP_CRC32 VALUES (853044451)
 INSERT INTO #_CVP_CRC32 VALUES (1172266101)
 INSERT INTO #_CVP_CRC32 VALUES (3705015759)
 INSERT INTO #_CVP_CRC32 VALUES (2882616665)
 INSERT INTO #_CVP_CRC32 VALUES (651767980)
 INSERT INTO #_CVP_CRC32 VALUES (1373503546)
 INSERT INTO #_CVP_CRC32 VALUES (3369554304)
 INSERT INTO #_CVP_CRC32 VALUES (3218104598)
 INSERT INTO #_CVP_CRC32 VALUES (565507253)
 INSERT INTO #_CVP_CRC32 VALUES (1454621731)
 INSERT INTO #_CVP_CRC32 VALUES (3485111705)
 INSERT INTO #_CVP_CRC32 VALUES (3099436303)
 INSERT INTO #_CVP_CRC32 VALUES (671266974)
 INSERT INTO #_CVP_CRC32 VALUES (1594198024)
 INSERT INTO #_CVP_CRC32 VALUES (3322730930)
 INSERT INTO #_CVP_CRC32 VALUES (2970347812)
 INSERT INTO #_CVP_CRC32 VALUES (795835527)
 INSERT INTO #_CVP_CRC32 VALUES (1483230225)
 INSERT INTO #_CVP_CRC32 VALUES (3244367275)
 INSERT INTO #_CVP_CRC32 VALUES (3060149565)
 INSERT INTO #_CVP_CRC32 VALUES (1994146192)
 INSERT INTO #_CVP_CRC32 VALUES (31158534)
 INSERT INTO #_CVP_CRC32 VALUES (2563907772)
 INSERT INTO #_CVP_CRC32 VALUES (4023717930)
 INSERT INTO #_CVP_CRC32 VALUES (1907459465)
 INSERT INTO #_CVP_CRC32 VALUES (112637215)
 INSERT INTO #_CVP_CRC32 VALUES (2680153253)
 INSERT INTO #_CVP_CRC32 VALUES (3904427059)
 INSERT INTO #_CVP_CRC32 VALUES (2013776290)
 INSERT INTO #_CVP_CRC32 VALUES (251722036)
 INSERT INTO #_CVP_CRC32 VALUES (2517215374)
 INSERT INTO #_CVP_CRC32 VALUES (3775830040)
 INSERT INTO #_CVP_CRC32 VALUES (2137656763)
 INSERT INTO #_CVP_CRC32 VALUES (141376813)
 INSERT INTO #_CVP_CRC32 VALUES (2439277719)
 INSERT INTO #_CVP_CRC32 VALUES (3865271297)
 INSERT INTO #_CVP_CRC32 VALUES (1802195444)
 INSERT INTO #_CVP_CRC32 VALUES (476864866)
 INSERT INTO #_CVP_CRC32 VALUES (2238001368)
 INSERT INTO #_CVP_CRC32 VALUES (4066508878)
 INSERT INTO #_CVP_CRC32 VALUES (1812370925)
 INSERT INTO #_CVP_CRC32 VALUES (453092731)
 INSERT INTO #_CVP_CRC32 VALUES (2181625025)
 INSERT INTO #_CVP_CRC32 VALUES (4111451223)
 INSERT INTO #_CVP_CRC32 VALUES (1706088902)
 INSERT INTO #_CVP_CRC32 VALUES (314042704)
 INSERT INTO #_CVP_CRC32 VALUES (2344532202)
 INSERT INTO #_CVP_CRC32 VALUES (4240017532)
 INSERT INTO #_CVP_CRC32 VALUES (1658658271)
 INSERT INTO #_CVP_CRC32 VALUES (366619977)
 INSERT INTO #_CVP_CRC32 VALUES (2362670323)
 INSERT INTO #_CVP_CRC32 VALUES (4224994405)
 INSERT INTO #_CVP_CRC32 VALUES (1303535960)
 INSERT INTO #_CVP_CRC32 VALUES (984961486)
 INSERT INTO #_CVP_CRC32 VALUES (2747007092)
 INSERT INTO #_CVP_CRC32 VALUES (3569037538)
 INSERT INTO #_CVP_CRC32 VALUES (1256170817)
 INSERT INTO #_CVP_CRC32 VALUES (1037604311)
 INSERT INTO #_CVP_CRC32 VALUES (2765210733)
 INSERT INTO #_CVP_CRC32 VALUES (3554079995)
 INSERT INTO #_CVP_CRC32 VALUES (1131014506)
 INSERT INTO #_CVP_CRC32 VALUES (879679996)
 INSERT INTO #_CVP_CRC32 VALUES (2909243462)
 INSERT INTO #_CVP_CRC32 VALUES (3663771856)
 INSERT INTO #_CVP_CRC32 VALUES (1141124467)
 INSERT INTO #_CVP_CRC32 VALUES (855842277)
 INSERT INTO #_CVP_CRC32 VALUES (2852801631)
 INSERT INTO #_CVP_CRC32 VALUES (3708648649)
 INSERT INTO #_CVP_CRC32 VALUES (1342533948)
 INSERT INTO #_CVP_CRC32 VALUES (654459306)
 INSERT INTO #_CVP_CRC32 VALUES (3188396048)
 INSERT INTO #_CVP_CRC32 VALUES (3373015174)
 INSERT INTO #_CVP_CRC32 VALUES (1466479909)
 INSERT INTO #_CVP_CRC32 VALUES (544179635)
 INSERT INTO #_CVP_CRC32 VALUES (3110523913)
 INSERT INTO #_CVP_CRC32 VALUES (3462522015)
 INSERT INTO #_CVP_CRC32 VALUES (1591671054)
 INSERT INTO #_CVP_CRC32 VALUES (702138776)
 INSERT INTO #_CVP_CRC32 VALUES (2966460450)
 INSERT INTO #_CVP_CRC32 VALUES (3352799412)
 INSERT INTO #_CVP_CRC32 VALUES (1504918807)
 INSERT INTO #_CVP_CRC32 VALUES (783551873)
 INSERT INTO #_CVP_CRC32 VALUES (3082640443)
 INSERT INTO #_CVP_CRC32 VALUES (3233442989)
 INSERT INTO #_CVP_CRC32 VALUES (3988292384)
 INSERT INTO #_CVP_CRC32 VALUES (2596254646)
 INSERT INTO #_CVP_CRC32 VALUES (62317068)
 INSERT INTO #_CVP_CRC32 VALUES (1957810842)
 INSERT INTO #_CVP_CRC32 VALUES (3939845945)
 INSERT INTO #_CVP_CRC32 VALUES (2647816111)
 INSERT INTO #_CVP_CRC32 VALUES (81470997)
 INSERT INTO #_CVP_CRC32 VALUES (1943803523)
 INSERT INTO #_CVP_CRC32 VALUES (3814918930)
 INSERT INTO #_CVP_CRC32 VALUES (2489596804)
 INSERT INTO #_CVP_CRC32 VALUES (225274430)
 INSERT INTO #_CVP_CRC32 VALUES (2053790376)
 INSERT INTO #_CVP_CRC32 VALUES (3826175755)
 INSERT INTO #_CVP_CRC32 VALUES (2466906013)
 INSERT INTO #_CVP_CRC32 VALUES (167816743)
 INSERT INTO #_CVP_CRC32 VALUES (2097651377)
 INSERT INTO #_CVP_CRC32 VALUES (4027552580)
 INSERT INTO #_CVP_CRC32 VALUES (2265490386)
 INSERT INTO #_CVP_CRC32 VALUES (503444072)
 INSERT INTO #_CVP_CRC32 VALUES (1762050814)
 INSERT INTO #_CVP_CRC32 VALUES (4150417245)
 INSERT INTO #_CVP_CRC32 VALUES (2154129355)
 INSERT INTO #_CVP_CRC32 VALUES (426522225)
 INSERT INTO #_CVP_CRC32 VALUES (1852507879)
 INSERT INTO #_CVP_CRC32 VALUES (4275313526)
 INSERT INTO #_CVP_CRC32 VALUES (2312317920)
 INSERT INTO #_CVP_CRC32 VALUES (282753626)
 INSERT INTO #_CVP_CRC32 VALUES (1742555852)
 INSERT INTO #_CVP_CRC32 VALUES (4189708143)
 INSERT INTO #_CVP_CRC32 VALUES (2394877945)
 INSERT INTO #_CVP_CRC32 VALUES (397917763)
 INSERT INTO #_CVP_CRC32 VALUES (1622183637)
 INSERT INTO #_CVP_CRC32 VALUES (3604390888)
 INSERT INTO #_CVP_CRC32 VALUES (2714866558)
 INSERT INTO #_CVP_CRC32 VALUES (953729732)
 INSERT INTO #_CVP_CRC32 VALUES (1340076626)
 INSERT INTO #_CVP_CRC32 VALUES (3518719985)
 INSERT INTO #_CVP_CRC32 VALUES (2797360999)
 INSERT INTO #_CVP_CRC32 VALUES (1068828381)
 INSERT INTO #_CVP_CRC32 VALUES (1219638859)
 INSERT INTO #_CVP_CRC32 VALUES (3624741850)
 INSERT INTO #_CVP_CRC32 VALUES (2936675148)
 INSERT INTO #_CVP_CRC32 VALUES (906185462)
 INSERT INTO #_CVP_CRC32 VALUES (1090812512)
 INSERT INTO #_CVP_CRC32 VALUES (3747672003)
 INSERT INTO #_CVP_CRC32 VALUES (2825379669)
 INSERT INTO #_CVP_CRC32 VALUES (829329135)
 INSERT INTO #_CVP_CRC32 VALUES (1181335161)
 INSERT INTO #_CVP_CRC32 VALUES (3412177804)
 INSERT INTO #_CVP_CRC32 VALUES (3160834842)
 INSERT INTO #_CVP_CRC32 VALUES (628085408)
 INSERT INTO #_CVP_CRC32 VALUES (1382605366)
 INSERT INTO #_CVP_CRC32 VALUES (3423369109)
 INSERT INTO #_CVP_CRC32 VALUES (3138078467)
 INSERT INTO #_CVP_CRC32 VALUES (570562233)
 INSERT INTO #_CVP_CRC32 VALUES (1426400815)
 INSERT INTO #_CVP_CRC32 VALUES (3317316542)
 INSERT INTO #_CVP_CRC32 VALUES (2998733608)
 INSERT INTO #_CVP_CRC32 VALUES (733239954)
 INSERT INTO #_CVP_CRC32 VALUES (1555261956)
 INSERT INTO #_CVP_CRC32 VALUES (3268935591)
 INSERT INTO #_CVP_CRC32 VALUES (3050360625)
 INSERT INTO #_CVP_CRC32 VALUES (752459403)
 INSERT INTO #_CVP_CRC32 VALUES (1541320221)
 INSERT INTO #_CVP_CRC32 VALUES (2607071920)
 INSERT INTO #_CVP_CRC32 VALUES (3965973030)
 INSERT INTO #_CVP_CRC32 VALUES (1969922972)
 INSERT INTO #_CVP_CRC32 VALUES (40735498)
 INSERT INTO #_CVP_CRC32 VALUES (2617837225)
 INSERT INTO #_CVP_CRC32 VALUES (3943577151)
 INSERT INTO #_CVP_CRC32 VALUES (1913087877)
 INSERT INTO #_CVP_CRC32 VALUES (83908371)
 INSERT INTO #_CVP_CRC32 VALUES (2512341634)
 INSERT INTO #_CVP_CRC32 VALUES (3803740692)
 INSERT INTO #_CVP_CRC32 VALUES (2075208622)
 INSERT INTO #_CVP_CRC32 VALUES (213261112)
 INSERT INTO #_CVP_CRC32 VALUES (2463272603)
 INSERT INTO #_CVP_CRC32 VALUES (3855990285)
 INSERT INTO #_CVP_CRC32 VALUES (2094854071)
 INSERT INTO #_CVP_CRC32 VALUES (198958881)
 INSERT INTO #_CVP_CRC32 VALUES (2262029012)
 INSERT INTO #_CVP_CRC32 VALUES (4057260610)
 INSERT INTO #_CVP_CRC32 VALUES (1759359992)
 INSERT INTO #_CVP_CRC32 VALUES (534414190)
 INSERT INTO #_CVP_CRC32 VALUES (2176718541)
 INSERT INTO #_CVP_CRC32 VALUES (4139329115)
 INSERT INTO #_CVP_CRC32 VALUES (1873836001)
 INSERT INTO #_CVP_CRC32 VALUES (414664567)
 INSERT INTO #_CVP_CRC32 VALUES (2282248934)
 INSERT INTO #_CVP_CRC32 VALUES (4279200368)
 INSERT INTO #_CVP_CRC32 VALUES (1711684554)
 INSERT INTO #_CVP_CRC32 VALUES (285281116)
 INSERT INTO #_CVP_CRC32 VALUES (2405801727)
 INSERT INTO #_CVP_CRC32 VALUES (4167216745)
 INSERT INTO #_CVP_CRC32 VALUES (1634467795)
 INSERT INTO #_CVP_CRC32 VALUES (376229701)
 INSERT INTO #_CVP_CRC32 VALUES (2685067896)
 INSERT INTO #_CVP_CRC32 VALUES (3608007406)
 INSERT INTO #_CVP_CRC32 VALUES (1308918612)
 INSERT INTO #_CVP_CRC32 VALUES (956543938)
 INSERT INTO #_CVP_CRC32 VALUES (2808555105)
 INSERT INTO #_CVP_CRC32 VALUES (3495958263)
 INSERT INTO #_CVP_CRC32 VALUES (1231636301)
 INSERT INTO #_CVP_CRC32 VALUES (1047427035)
 INSERT INTO #_CVP_CRC32 VALUES (2932959818)
 INSERT INTO #_CVP_CRC32 VALUES (3654703836)
 INSERT INTO #_CVP_CRC32 VALUES (1088359270)
 INSERT INTO #_CVP_CRC32 VALUES (936918000)
 INSERT INTO #_CVP_CRC32 VALUES (2847714899)
 INSERT INTO #_CVP_CRC32 VALUES (3736837829)
 INSERT INTO #_CVP_CRC32 VALUES (1202900863)
 INSERT INTO #_CVP_CRC32 VALUES (817233897)
 INSERT INTO #_CVP_CRC32 VALUES (3183342108)
 INSERT INTO #_CVP_CRC32 VALUES (3401237130)
 INSERT INTO #_CVP_CRC32 VALUES (1404277552)
 INSERT INTO #_CVP_CRC32 VALUES (615818150)
 INSERT INTO #_CVP_CRC32 VALUES (3134207493)
 INSERT INTO #_CVP_CRC32 VALUES (3453421203)
 INSERT INTO #_CVP_CRC32 VALUES (1423857449)
 INSERT INTO #_CVP_CRC32 VALUES (601450431)
 INSERT INTO #_CVP_CRC32 VALUES (3009837614)
 INSERT INTO #_CVP_CRC32 VALUES (3294710456)
 INSERT INTO #_CVP_CRC32 VALUES (1567103746)
 INSERT INTO #_CVP_CRC32 VALUES (711928724)
 INSERT INTO #_CVP_CRC32 VALUES (3020668471)
 INSERT INTO #_CVP_CRC32 VALUES (3272380065)
 INSERT INTO #_CVP_CRC32 VALUES (1510334235)
 INSERT INTO #_CVP_CRC32 VALUES (755167117)
END -- dbo._CVP_FILLCRC32
GO




IF NOT OBJECT_ID('dbo._CVP_SS') IS NULL DROP FUNCTION dbo._CVP_SS
GO
CREATE FUNCTION dbo._CVP_SS(@lcSTRING VARCHAR(MAX), @lcSEP VARCHAR(10))
RETURNS TABLE
AS
 --http://stackoverflow.com/questions/2647/split-string-in-sql
 RETURN (WITH tokens(ORD, FPOS, TPOS, LSEP) AS
          (
          SELECT CAST(1 AS BIGINT), CAST(1 AS BIGINT), CASE WHEN CHARINDEX(@lcSEP, @lcSTRING,1)-1<0 THEN LEN('x'+@lcString+'x')-2 ELSE CHARINDEX(@lcSEP, @lcSTRING,1)-1 END, LEN('x'+@lcSEP+'x')-2
          UNION ALL
          SELECT ORD + 1, TPOS + LSEP+1, CASE WHEN CHARINDEX(@lcSEP, @lcSTRING, TPOS + LSEP+1)=0 THEN LEN('x'+@lcString+'x')-2 ELSE CHARINDEX(@lcSEP, @lcSTRING, TPOS + LSEP+1)-1 END, LSEP
            FROM tokens
            WHERE TPOS <LEN('x'+@lcString+'x')-2
          )
         SELECT FPOS, CASE WHEN TPOS<FPOS THEN FPOS ELSE TPOS END AS TPOS, ORD , SUBSTRING( @lcSTRING, FPOS,TPOS-FPOS+1) AS FIELD, TPOS-FPOS+1 AS LFIELD
          FROM tokens
        )
GO

IF NOT OBJECT_ID('dbo._CVP_SAVELOG') IS NULL DROP PROCEDURE dbo._CVP_SAVELOG
GO
CREATE PROCEDURE dbo._CVP_SAVELOG(@lcTRC NVARCHAR(1000), @lcFOLDER NVARCHAR(1000), @lcSHORTFILENAME NVARCHAR(1000), @liMODE INT=1, @liMAXNESTLEVEL INT=0 OUT)
AS
BEGIN
 DECLARE @lorsData CURSOR, @lorsNext CURSOR
 DECLARE @liErr INT, @liErrX INT, @loFSO INT, @lcMSG VARCHAR(MAX), @liFLAG INT, @lcFile VARCHAR(2000), @liCNT INT, @liROWS INT, @liNROW INT, 
         @lcLINE VARCHAR(MAX), @liS BIGINT, @liNESTLEVELZ INT, @ltT1 DATETIME, @lcNAME NVARCHAR(128), @liID INT, @liDBID INT,
         @lcSOURCE NVARCHAR(MAX), @lcLINESRC  NVARCHAR(MAX), @lcCRC32 VARCHAR(10), @lii INT

 DECLARE @lcSQL NVARCHAR(MAX), @lcSQL2 NVARCHAR(MAX), @lcDQ NVARCHAR(MAX), @lcPom NVARCHAR(128)
 DECLARE @ldSTARTTIME DATETIME, @lcPROC NVARCHAR(256), @lcFILENAME NVARCHAR(1000), 
         @liLVL INT, @liDatabaseidO INT, @liObjectidO INT, @liLINE INT, @liNESTLEVELD INT, @loADOSO INT, @liNESTLEVELO INT,
         @liEVENTCLASS INT, @liEVENTSEQUENCE BIGINT, @liDatabaseid INT, @liLINENUMBER INT, @liObjectid INT,
         @liNESTLEVEL INT, @liREQUESTID INT, @liOBJECTTYPE INT, @lcTEXTDATA NVARCHAR(MAX), @liOFFSET INT, @lnDURATION NUMERIC(20,6),
         @liEVENTCLASS_N INT, @liEVENTSEQUENCE_N BIGINT, @liDatabaseid_N INT, @liLINENUMBER_N INT, @liObjectid_N INT,
         @liNESTLEVEL_N INT, @liREQUESTID_N INT, @liOBJECTTYPE_N INT, @lcTEXTDATA_N NVARCHAR(MAX), @liOFFSET_N INT, @lnDURATION_N NUMERIC(20,6),
         @liDATABASEID_DQ INT, @liOBJECTID_DQ INT, @liEVENTSEQUENCE_DQ BIGINT, @liMAXCNT BIGINT, @liCURRCNT BIGINT, @liCURRP INT, @liLASTP INT,
         @liDELTACNT INT, @lcOWNER NVARCHAR(128)

 --DECLARE @loNESTLEVEL  TABLE (ID INT IDENTITY(0,1) NOT NULL, NESTLEVELO INT, PRIMARY KEY (ID))
 
 SELECT * INTO #OBJTYPELIST FROM dbo._CVP_OBJTLIST() 

 CREATE TABLE #_CVP_CRC32 (ID INT IDENTITY(0,1) NOT NULL, Value BIGINT, PRIMARY KEY (ID))
 CREATE TABLE #DQ (DATABASEID INT, OBJECTID INT, EVENTSEQUENCE BIGINT, CRC32 VARCHAR(10), PRIMARY KEY (CRC32))
 EXEC dbo._CVP_FILLCRC32

 EXECUTE @liErr = sp_OACreate  'Scripting.FileSystemObject' , @loFSO OUT

 IF @liErr<>0 GOTO _CVP_SAVELOG_END

 SET @lcFOLDER=@lcFOLDER+CASE WHEN RIGHT(@lcFOLDER,1)<>'\' THEN '\' ELSE '' END

 SET @lcFile=@lcFOLDER+@lcSHORTFILENAME+'.log'

 -- kontrola zda existuje složka
 EXECUTE @liErr = sp_OAMethod   @loFSO, 'FolderExists',  @liFLAG OUT, @lcFOLDER
 IF @liErr<>0 BEGIN 
    GOTO _CVP_SAVELOG_END
 END 
 IF @liFLAG=0 BEGIN
    SET @lcMSG=REPLACE('Neexistuje adresář pro uložení souborů %DIR%. Export zrušen.','%DIR%',@lcFOLDER)
    PRINT @lcMSG
    GOTO _CVP_SAVELOG_END
 END

 SET @ltT1=GETDATE()



 CREATE TABLE #DUR (EventSequence BIGINT, OFFSET INT, DURATION FLOAT, PRIMARY KEY (OFFSET,EventSequence))
 INSERT INTO #DUR
   SELECT EventSequence, COALESCE(OFFSET, -1), DURATION FROM ::fn_trace_gettable(@lcTRC, DEFAULT)  AA WHERE EVENTCLASS IN (12, 45)
 PRINT '#DUR '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))

 SET @liMAXCNT=(SELECT COUNT_BIG(1) FROM #DUR)*2
 SET @liCURRCNT=0
 SET @liDELTACNT=1000 

 EXECUTE @liErr = sp_OACreate  'ADODB.Stream' , @loADOSO OUT
 EXECUTE @liErr = sp_OASetProperty  @loADOSO, 'Mode', 3 --Read/Write
 EXECUTE @liErr = sp_OASetProperty  @loADOSO, 'Type', 2 --text
 EXECUTE @liErr = sp_OASetProperty  @loADOSO, 'Charset', 'Windows-1250'
 EXECUTE @liErr = sp_OAMethod  @loADOSO, 'Open', Null
 
 SET @lcDQ='''CREATE PROCEDURE ''+@lcOWNER+''.[''+CAST(@liOBJECTID AS VARCHAR(30))+''] AS ''+CHAR(13)+''BEGIN''+CHAR(13)+COALESCE(REPLACE(REPLACE(@lcTEXTDATA,CHAR(13)+CHAR(10),CHAR(13)),CHAR(10),CHAR(13)),''EXECUTE SQL'')+CHAR(13)+''END''+CHAR(13)'


 -- Vytvoř dle zdrojové tabulky log soubor pro VFP
 SET @ltT1=GETDATE()
 SET @lorsData = CURSOR LOCAL READ_ONLY FOR
     SELECT CASE EVENTCLASS WHEN 13 THEN 44 WHEN 12 THEN 45 ELSE EVENTCLASS END AS EVENTCLASS, 
            EVENTSEQUENCE, Databaseid, 
            CASE ObjectType WHEN 20801 THEN 3 WHEN 20816 THEN 3 ELSE COALESCE(Linenumber, 3) END AS Linenumber, 
            COALESCE(Objectid, -EVENTSEQUENCE) , COALESCE(NESTLEVEL, 1), REQUESTID, COALESCE(OBJECTTYPE, -1) AS OBJECTTYPE, 
            CASE WHEN ObjectType IN (20801, 20816) THEN TEXTDATA
                 WHEN Objectid<0 THEN TEXTDATA 
                 WHEN eventclass=13  THEN TEXTDATA 
                 ELSE NULL END AS TEXTDATA, COALESCE(OFFSET, -1), Duration/1000000.0000
       FROM ::fn_trace_gettable(@lcTRC, DEFAULT) 
       WHERE STATE IS NULL AND eventclass IN (44,45,13,12)
 OPEN @lorsData


 PRINT 'OPEN CURSOR '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))

 SET @liDatabaseidO=-1
 SET @liObjectidO=-1
 SET @liNESTLEVELZ=0
 SET @liNESTLEVELD=0
 SET @liNESTLEVELO=-1

 SET @liLASTP=0

 WHILE 0 = 0 BEGIN
   LOOP1:
   FETCH NEXT FROM @lorsData INTO @liEVENTCLASS, @liEVENTSEQUENCE, @liDatabaseid, @liLinenumber, @liObjectid, @liNESTLEVEL, @liREQUESTID, @liOBJECTTYPE, @lcTEXTDATA, @liOFFSET, @lnDURATION
   IF @@FETCH_STATUS <> 0 BREAK
   SET @liCURRCNT=@liCURRCNT+1

   --PRINT 'HEADER'
   --PRINT dbo.To_CHAR(@liEVENTSEQUENCE,0)

   IF @liEVENTCLASS=45  BEGIN
      CONTINUE
   END

   SET @liCURRCNT=@liCURRCNT+1
   LOOP2:
   FETCH NEXT FROM @lorsData INTO @liEVENTCLASS_N, @liEVENTSEQUENCE_N, @liDatabaseid_N, @liLinenumber_N, @liObjectid_N, @liNESTLEVEL_N, @liREQUESTID_N, @liOBJECTTYPE_N, @lcTEXTDATA_N, @liOFFSET_N, @lnDURATION_N
   IF @@FETCH_STATUS <> 0 BREAK

   SET @liCURRP=(@liCURRCNT/(@liMAXCNT*1.0000))*100.000
   IF @liCURRCNT%@liDELTACNT=0 BEGIN
      PRINT @liCURRCNT
   END
   IF @liCURRP%5=0 BEGIN
      IF @liCURRP<>@liLASTP BEGIN
         PRINT '========'
         PRINT '= '+RIGHT('    '+CAST(@liCURRP AS VARCHAR(30))+'%',4)+' ='
         PRINT '========'
         SET @liLASTP=@liCURRP
      END
   END
   IF @liCURRCNT>@liMAXCNT BEGIN
      PRINT dbo.TO_CHAR(@liEVENTSEQUENCE,0)+' '+dbo.TO_CHAR(@liEVENTSEQUENCE_N,0)+' '+ dbo.TO_CHAR(@liCURRCNT,0)+' '+dbo.TO_CHAR(@liMAXCNT,0)
      IF @liEVENTSEQUENCE=@liEVENTSEQUENCE_N BEGIN
         PRINT 'Neverending LOOP'
         BREAK
      END
   END


   --PRINt 'LOOP0: '+dbo.To_CHAR(@liEVENTCLASS,0)+' '+dbo.To_CHAR(@liEVENTSEQUENCE,0)+' '+dbo.To_CHAR(@liEVENTCLASS_N,0)+' '+dbo.To_CHAR(@liEVENTSEQUENCE_N,0)

   IF @liDatabaseidO<>@liDatabaseid BEGIN
      SELECT @liDBID=ID, @lcNAME=NAME, @lcFILENAME=FILENAME FROM #DBs WHERE databaseid=@liDatabaseid
      IF @@ROWCOUNT=0 BEGIN
         INSERT INTO #DBs 
           SELECT DATABASE_ID, NAME, 
                  REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@lcSHORTFILENAME+'_'+CAST(DATABASE_ID AS VARCHAR(30)),'[',''), '\',''), '/',''), ':',''), '*',''), '?',''), '"',''), '<',''), '>',''), '|',''), ']','')+'.tsql'
             FROM  sys.databases 
             WHERE database_id=@liDatabaseid
         SELECT @liDBID=ID, @lcNAME=NAME, @lcFILENAME=FILENAME FROM #DBs WHERE databaseid=@liDatabaseid
      END
      SET @liDatabaseidO=ISNULL(@liDatabaseid,-1)
   END
   --END IF @liDatabaseidO<>@liDatabaseid


   SET @lcTEXTDATA=REPLACE(@lcTEXTDATA, NCHAR(0x00) COLLATE Latin1_General_BIN, N'') -- remove \0

   --PRINt 'LOOP: '+dbo.To_CHAR(OBJECT_NAME(@liOBJECTID),0)+' '+dbo.To_CHAR(@liOBJECTID,0)+' '+dbo.To_CHAR(@liObjectType,0)+' '+dbo.To_CHAR(@liEVENTSEQUENCE,0)+' '+dbo.To_CHAR(@liOBJECTIDO,0)+' '+dbo.TO_CHAR(@lnDURATION,0)+' '+dbo.TO_CHAR(@liLinenumber,0)+' '+dbo.TO_CHAR(CAST(@lcTEXTDATA AS VARCHAR(4000)),0)
   --PRINt 'LOOPX: '+dbo.To_CHAR(OBJECT_NAME(@liOBJECTIDO),0)+' '+dbo.To_CHAR(@liOBJECTIDO,0)

   IF @liObjectIDO<>@liObjectID OR @liObjectType IN (20801, 20816) BEGIN

      IF NOT @liObjectType IN (20801, 20816) BEGIN
         SELECT @liID=ID, @lcPROC=OWNER+'.'+NAME
           FROM #OBJECTs 
           WHERE DATABASEID=@liDATABASEID AND OBJECTID=@liOBJECTID AND EVENTSEQUENCE=CASE WHEN @liOBJECTID<0 THEN EVENTSEQUENCE ELSE -1 END
         SET @liCNT=@@ROWCOUNT

         SELECT @liDATABASEID_DQ=@liDATABASEID, @liOBJECTID_DQ=@liOBJECTID, @liEVENTSEQUENCE_DQ=CASE WHEN @liOBJECTID<0 THEN @liEVENTSEQUENCE ELSE -1 END

         IF @liCNT=0 BEGIN
            SET @lcSQL='INSERT INTO #OBJECTs '+
                       '  SELECT @liDATABASEID, @liOBJECTID, -1, AC.NAME, AB.NAME, REPLACE(REPLACE(AD.[definition],CHAR(13)+CHAR(10),CHAR(13)),CHAR(10),CHAR(13)), 0,0,1'+
                       '    FROM '+@lcNAME+'.sys.all_objects AB INNER JOIN '+@lcNAME+'.sys.schemas         AC ON AB.schema_id=AC.schema_id'+
                       '                                        INNER JOIN '+@lcNAME+'.sys.all_sql_modules AD ON AB.object_id=AD.object_id'+
                       '    WHERE ABS(AB.object_id)=@liOBJECTID'
             EXEC sp_executesql @lcSQL, N'@liDATABASEID INT, @liOBJECTID INT', @liDATABASEID, @liOBJECTID

            SET @liCNT=CASE WHEN @@ROWCOUNT=0 THEN -1 ELSE 0 END

            -- check if code not is null
            DECLARE @liLinenumberX BIGINT, @lcTEXTDATAX NVARCHAR(MAX), @lcMODNAME NVARCHAR(128)
            IF @liCNT=0 BEGIN
               SELECT @lcTEXTDATAX=SOURCE, @liID=ID, @lcMODNAME="NAME"
                 FROM #OBJECTs 
                 WHERE DATABASEID=@liDATABASEID AND OBJECTID=@liOBJECTID AND EVENTSEQUENCE=CASE WHEN @liOBJECTID<0 THEN EVENTSEQUENCE ELSE -1 END

               IF @lcTEXTDATAX IS NULL BEGIN
                  SELECT @liLinenumberX=3, @lcTEXTDATA=''
                  SELECT @lcTEXTDATAX=REPLACE(REPLACE(TEXTDATA, CHAR(13)+CHAR(10), CHAR(13)), CHAR(10), CHAR(13)),
                         @lcTEXTDATA=@lcTEXTDATA+CASE WHEN Linenumber>@liLinenumberX THEN REPLICATE(CHAR(13), Linenumber-@liLinenumberX) ELSE '' END+@lcTEXTDATAX,
                         @liLinenumberX=Linenumber+LEN(@lcTEXTDATAX)-LEN(REPLACE(@lcTEXTDATAX, CHAR(13), ''))
                    FROM (SELECT DISTINCT Linenumber, CAST(TEXTDATA AS VARCHAR(8000)) AS TEXTDATA
                            FROM ::fn_trace_gettable(@lcTRC, DEFAULT) 
                            WHERE STATE IS NULL AND eventclass IN (44,13) AND Databaseid=@liDATABASEID AND COALESCE(Objectid, -EVENTSEQUENCE)=@liOBJECTID
                         ) AA
                    ORDER BY Linenumber

                  SELECT @liLinenumber=3,
                         @lcSQL='UPDATE #OBJECTs SET SOURCE='+@lcDQ+' WHERE ID=@liID'

                  EXEC sp_executesql @lcSQL, 
                                     N'@liID INT, @liOBJECTID VARCHAR(30), @lcTEXTDATA NVARCHAR(MAX), @lcOWNER NVARCHAR(128)', 
                                     @liID, @lcMODNAME, @lcTEXTDATA, 'dbo'
               END 
            END


            IF @liCNT=-1 BEGIN
               SET @lcOWNER='dbo'
               IF @liOBJECTID<0 BEGIN
                  SELECT @lcOWNER='dsql'
               END

               SET @liLinenumber=3
               SET @lcSQL='INSERT INTO #OBJECTs '+
                          '  SELECT @liDATABASEID, @liOBJECTID, @liEVENTSEQUENCE, @lcOWNER, CAST(@liOBJECTID AS VARCHAR(30)), '+
                          '         '+@lcDQ+',0,0,1'

               EXEC sp_executesql @lcSQL, 
                                  N'@liDATABASEID INT, @liOBJECTID INT, @liEVENTSEQUENCE INT, @lcTEXTDATA NVARCHAR(MAX), @lcOWNER NVARCHAR(128)', 
                                  @liDATABASEID, @liOBJECTID, @liEVENTSEQUENCE_DQ, @lcTEXTDATA, @lcOWNER
              
            END
         END
         --END IF @liCNT=0
         IF @liCNT>0 BEGIN
            UPDATE #OBJECTs SET RUNS=RUNS+1 WHERE ID=@liID
         END
         --END IF @liCNT>0
         END
      ELSE BEGIN
         EXEC dbo._CVP_CRC32 @lcTEXTDATA, @lcCRC32 OUT
         SELECT @liDATABASEID_DQ=DATABASEID, @liOBJECTID_DQ=OBJECTID, @liEVENTSEQUENCE_DQ=EVENTSEQUENCE, @liCNT=1 FROM #DQ WHERE CRC32=@lcCRC32
         IF @@ROWCOUNT=0 BEGIN
            SELECT @liDATABASEID_DQ=@liDATABASEID, @liOBJECTID_DQ=@liOBJECTID, @liEVENTSEQUENCE_DQ=@liEVENTSEQUENCE, @liCNT=0
            INSERT INTO #DQ (DATABASEID, OBJECTID, EVENTSEQUENCE, CRC32) VALUES (@liDATABASEID, @liOBJECTID, @liEVENTSEQUENCE, @lcCRC32)

            SET @lcSQL='INSERT INTO #OBJECTs '+
                       '  SELECT @liDATABASEID, @liOBJECTID, @liEVENTSEQUENCE, @lcOWNER, CAST(@liEVENTSEQUENCE AS VARCHAR(30)), '+
                       '         '+@lcDQ+',1,0,1'

            EXEC sp_executesql @lcSQL, 
                               N'@liDATABASEID INT, @liOBJECTID INT, @liEVENTSEQUENCE INT, @lcTEXTDATA NVARCHAR(MAX), @lcOWNER NVARCHAR(128)', 
                               @liDATABASEID_DQ, @liOBJECTID_DQ, @liEVENTSEQUENCE_DQ, @lcTEXTDATA, 'dsql'

          END
          --END IF @liCNT=0

          SELECT @liID=ID, @lcPROC=OWNER+'.'+NAME FROM #OBJECTs WHERE DATABASEID=@liDATABASEID_DQ AND OBJECTID=@liOBJECTID_DQ AND EVENTSEQUENCE=@liEVENTSEQUENCE_DQ
          IF @liCNT>0 BEGIN
             UPDATE #OBJECTs SET RUNS=RUNS+1 WHERE ID=@liID
          END
          --END IF @liCNT>0

      END
      SET @liOBJECTIDO=ISNULL(@liOBJECTID,-1)

      IF @liCNT<=0 BEGIN
         SELECT @liID=ID, @lcPROC=OWNER+'.'+NAME, @liROWS=LEN('a'+SOURCE+'a')-LEN(REPLACE('a'+SOURCE+'a',CHAR(13),''))+1, 
                @lcSOURCE=CASE WHEN @liMODE IN (3,4) THEN SOURCE ELSE NULL END
           FROM #OBJECTs 
           WHERE DATABASEID=@liDATABASEID_DQ AND OBJECTID=@liOBJECTID_DQ AND EVENTSEQUENCE=CASE WHEN @liObjectType IN (20801,20816) OR @liOBJECTID_DQ<0 THEN @liEVENTSEQUENCE_DQ ELSE -1 END


         SELECT @liNROW=ISNULL(MAX(LINENUMBER),0) FROM #OBJECTLINs AA WHERE DATABASEID=@liDATABASEID_DQ;

         WITH tree(id) AS
           (SELECT 1
            UNION ALL
            SELECT AA.ID+AB.ID 
              FROM (SELECT 1 AS ID) AA INNER JOIN TREE AB ON 0=0
              WHERE AA.ID+AB.ID<=@liROWS
           )
          INSERT INTO #OBJECTLINs
            SELECT @liDATABASEID, @liID, @liNROW+ID, ID FROM tree
            OPTION (MAXRECURSION 32000)

         IF @liMode IN (3,4) BEGIN
            INSERT INTO #OBJECTSRCs (ID, ORD, LINE) SELECT @liID, ORD, FIELD FROM dbo._CVP_SS(@lcSOURCE,CHAR(13) ) OPTION (MAXRECURSION 32000)
         END;

      END
      --END IF @liCNT=0
   END
   --END IF @liObjectIDO<>@liObjectID


   --IF @liEVENTCLASS=44 AND (@liOBJECTTYPE=20801 OR @liOBJECTTYPE=20816) AND @liNESTLEVEL>1 BEGIN
   --   SELECT @liNESTLEVELD=1, @liNESTLEVELO=@liOBJECTID

   --   --PRINT 'DETECT'
   --   --PRINT dbo.To_CHAR(@liEVENTSEQUENCE,0)

   --   INSERT INTO @loNESTLEVEL (NESTLEVELO) VALUES (@liOBJECTID)
   --   --PRINT '@liNESTLEVEL @liNESTLEVELD @liNESTLEVELO '+dbo.TO_CHAR(@liNESTLEVEL,0)+' '++dbo.TO_CHAR(@liNESTLEVELD,0)+' '+dbo.TO_CHAR(@liNESTLEVELO,0)

   --END

--if @liobjectid=974834735 BEGIN
--PRINT @liLinenumber
--  SELECT @liLinenumber, @liLinenumber_N, * FROM #OBJECTLINs WHERE ID=@liID --AND ORD=@liLinenumber
--END

   SELECT @liLVL=@liNESTLEVEL-CASE @liNESTLEVELD WHEN 1 THEN 1 ELSE 0 END,
          @lnDURATION=COALESCE(@lnDURATION_N,(SELECT TOP 1 Duration/1000000.0000
                                              FROM #DUR
                                              WHERE OFFSET=@liOFFSET AND EVENTSEQUENCE>@liEVENTSEQUENCE
                                              ORDER BY EVENTSEQUENCE ASC),0
                              ),
          @liLINE=(SELECT LINENUMBER FROM #OBJECTLINs WHERE ID=@liID AND ORD=@liLinenumber)


--if @liobjectid=974834735 BEGIN
--PRINT @liLine
--END

   SELECT @liMAXNESTLEVEL= CASE WHEN @liMAXNESTLEVEL<LVL THEN LVL ELSE @liMAXNESTLEVEL END,
          @liNESTLEVELZ=NESTLEVELZ, @liLVL=LVL
     FROM (SELECT CASE @liREQUESTID WHEN 0 THEN @liLVL ELSE @liNESTLEVELZ END AS NESTLEVELZ,
                  CASE @liREQUESTID WHEN 0 THEN @liLVL ELSE @liLVL+@liNESTLEVELZ END AS LVL
          ) AA

  -- PRINT '@liLVL '+dbo.TO_CHAR(@liLVL,0)

   UPDATE #OBJECTs SET DURATION_SUM=DURATION_SUM+@lnDURATION WHERE ID=@liID

   --PRINT dbo.TO_CHAR(@liID,0)+' '+dbo.TO_CHAR(@liLinenumber,0)

   IF @liMODE=2 BEGIN
      SET @lcLINE=CONVERT(VARCHAR(20),@lnDURATION,0)+',,'+CONVERT(VARCHAR(30),@liID,0)+','+CONVERT(VARCHAR(30),@liLINE,0)+','+CONVERT(VARCHAR(30),@liDBID,0)+','+CONVERT(VARCHAR(30),@liLVL,0)+CHAR(13)+CHAR(10)
      --IF @lcLINE IS NULL BEGIN
      --   PRINT dbo.To_CHAR(@liEVENTSEQUENCE,0)+', '+dbo.To_CHAR(@liEVENTSEQUENCE_DQ,0)+', '+dbo.TO_CHAR(@lnDURATION,0)+',,'+dbo.TO_CHAR(@liID,0)+','+dbo.TO_CHAR(@liLINE,0)+','+dbo.TO_CHAR(@liDBID,0)+','+dbo.TO_CHAR(@liLVL,0)
      --END
      END
   ELSE IF @liMODE=1 BEGIN
      SET @lcLINE=CONVERT(VARCHAR(20),@lnDURATION,0)+',,'+@lcPROC+','+CONVERT(VARCHAR(30),@liLINE,0)+','+@lcFILENAME+','+CONVERT(VARCHAR(30),@liLVL,0)+CHAR(13)+CHAR(10)
      --IF @lcLINE IS NULL BEGIN
      --   PRINT dbo.TO_CHAR(@lnDURATION,0)+',,'+dbo.TO_CHAR(@lcPROC,0)+','+dbo.TO_CHAR(@liLINE,0)+','+dbo.TO_CHAR(@lcFILENAME,0)+','+dbo.TO_CHAR(@liLVL,0)
      --END
      END
   ELSE IF @liMODE=3 BEGIN
      SELECT @lcLINESRC=(SELECT LINE FROM #OBJECTSRCs WHERE ID=@liID AND ORD=@liLinenumber),
             @lcLINE=CONVERT(VARCHAR(20),@lnDURATION,0)+',,'+@lcPROC+','+CONVERT(VARCHAR(30),@liLINE,0)+','+@lcFILENAME+','+CONVERT(VARCHAR(30),@liLVL,0)+','+@lcLINESRC+CHAR(13)+CHAR(10)
      END
   ELSE IF @liMODE=4 BEGIN
      SELECT @lcLINESRC=(SELECT LINE FROM #OBJECTSRCs WHERE ID=@liID AND ORD=@liLinenumber),
             @lcPom=(SELECT OBJECTTYPENAME FROM #OBJTYPELIST WHERE OBJECTTYPEID=@liOBJECTTYPE),
             @lcLINE=CONVERT(VARCHAR(20),@lnDURATION,0)+',,'+@lcPROC+','+CONVERT(VARCHAR(30),@liLINE,0)+','+@lcFILENAME+','+ISNULL(CONVERT(VARCHAR(30),@liLVL,0),'NULL')+': '+ISNULL(@lcPom,'NULL')+','+ISNULL(CONVERT(VARCHAR(30),@liLINENUMBER,0),'NULL')+','+ISNULL(CONVERT(VARCHAR(30),@liNESTLEVEL,0),'NULL')+','+ISNULL(@lcLINESRC,'NULL')+CHAR(13)+CHAR(10)
   END


  -- PRINT @lcLINE
  --dbo._CVP_OBJTLIST
  SET @lcLINE=COALESCE(@lcLINE,'')

   EXECUTE @liErr = sp_OAMethod  @loADOSO, 'WriteText', NULL, @lcLINE

   IF @liEVENTCLASS_N=44 BEGIN
      SELECT @liEVENTCLASS=@liEVENTCLASS_N, @liEVENTSEQUENCE=@liEVENTSEQUENCE_N, @liDatabaseid=@liDatabaseid_N, @liLinenumber=@liLinenumber_N, 
             @liObjectid=@liObjectid_N, @liNESTLEVEL=@liNESTLEVEL_N, @liREQUESTID=@liREQUESTID_N, @liOBJECTTYPE=@liOBJECTTYPE_N, 
             @lcTEXTDATA=@lcTEXTDATA_N, @liOFFSET=@liOFFSET_N, @lnDURATION=@lnDURATION_N

      GOTO LOOP2
   END

 END
 CLOSE @lorsData
 DEALLOCATE @lorsData
 PRINT '========'
 PRINT '= 100% ='
 PRINT '========'

--select @liMAXNESTLEVEL
--select * from #OBJECTS order by EVENTSEQUENCE
 PRINT 'GENERATE STREAM '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))

 ---- zavři výstupní soubor
 SET @ltT1=GETDATE()
 EXECUTE @liErrX = sp_OAMethod  @loADOSO, 'SaveToFile', NULL, @lcFile, 2
 SET @liErr=@liErr|@liErrX
 PRINT 'SAVE TO FILE '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))
 EXECUTE sp_OAMethod  @loADOSO, 'Close', Null
 EXECUTE sp_OADestroy @loADOSO

 IF @liErr=0 BEGIN
    SET @lcMSG=REPLACE('Export dat do souboru %FILE%.','%FILE%',@lcFile)
    PRINT @lcMSG
 END

 IF @liErr<>0 BEGIN
    SET @lcMSG=REPLACE('Nelze vytvořit soubor %FILE%. Export zrušen.','%FILE%',@lcFile)
    PRINT @lcMSG
 END


 _CVP_SAVELOG_END:
 EXECUTE sp_OADestroy @loFSO

 IF NOT OBJECT_ID('tempdb.dbo.#OBJTYPELIST') IS NULL DROP TABLE #OBJTYPELIST
 IF NOT OBJECT_ID('tempdb.dbo.#DUR') IS NULL DROP TABLE #DUR
 IF NOT OBJECT_ID('tempdb.dbo.#_CVP_CRC32') IS NULL DROP TABLE #_CVP_CRC32
 IF NOT OBJECT_ID('tempdb.dbo.#DQ') IS NULL DROP TABLE #DQ

END --_CVP_SAVELOG
GO


IF NOT OBJECT_ID('dbo._CVP_PROCESS') IS NULL DROP PROCEDURE dbo._CVP_PROCESS
GO
CREATE PROCEDURE dbo._CVP_PROCESS(@lcTRC NVARCHAR(1000), @lcFOLDER NVARCHAR(1000), @lcSHORTFILENAME NVARCHAR(1000), @liMODE INT=1)
AS
BEGIN

 DECLARE @ltT1 DATETIME, @liMAXNESTLEVEL INT

 CREATE TABLE #DBs (ID INT IDENTITY(1,1), DATABASEID INT, NAME NVARCHAR(128), FILENAME NVARCHAR(100))
 CREATE TABLE #OBJECTs (ID INT IDENTITY(1,1), DATABASEID INT, OBJECTID INT, EVENTSEQUENCE INT, OWNER NVARCHAR(128), NAME NVARCHAR(128), SOURCE NVARCHAR(MAX), DQ NUMERIC(1), DURATION_SUM NUMERIC(20,6), RUNS BIGINT, UNIQUE CLUSTERED (DATABASEID, OBJECTID, EVENTSEQUENCE), PRIMARY KEY NONCLUSTERED (ID))
 CREATE TABLE #OBJECTLINs (DATABASEID INT, ID INT, LINENUMBER INT, ORD INT, PRIMARY KEY NONCLUSTERED (DATABASEID, LINENUMBER), UNIQUE CLUSTERED (ID, ORD))
 CREATE TABLE #OBJECTSRCs (ID INT, ORD INT, LINE NVARCHAR(MAX), UNIQUE CLUSTERED (ID, ORD))
 CREATE TABLE #STATS (DATABASEIDLEN INT, OBJECTIDLEN INT, NESTLEVELLEN INT)


 -- Vytvoř log dle zdrojového souboru
 SET @ltT1=GETDATE()
 SET @liMAXNESTLEVEL=0
 EXEC dbo._CVP_SAVELOG @lcTRC, @lcFOLDER, @lcSHORTFILENAME, @liMODE, @liMAXNESTLEVEL OUT
 PRINT 'PROCESS LOG '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))

 SET @ltT1=GETDATE()
 INSERT INTO #STATS (DATABASEIDLEN, OBJECTIDLEN, NESTLEVELLEN)
   SELECT MAX(LEN(CAST(AB.ID AS VARCHAR(30)))), MAX(LEN(CAST(AA.ID AS VARCHAR(30)))), MAX(LEN(CAST(@liMAXNESTLEVEL AS VARCHAR(30))))
     FROM #OBJECTs AA INNER JOIN #DBs AB ON AA.DATABASEID=AB.DATABASEID
 PRINT '#STATS '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))

 -- Vytvoř soubory dle načtených OBJECTs a naplň je zdrojovýma kódama
 SET @ltT1=GETDATE()
 EXEC dbo._CVP_SAVESRCS @lcFOLDER, @lcSHORTFILENAME, @liMODE
 PRINT 'SAVE SRC '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))

 IF NOT OBJECT_ID('tempdb.dbo.#DBs') IS NULL DROP TABLE #DBs
 IF NOT OBJECT_ID('tempdb.dbo.#OBJECTs') IS NULL DROP TABLE #OBJECTs
 IF NOT OBJECT_ID('tempdb.dbo.#OBJECTLINs') IS NULL DROP TABLE #OBJECTLINs
 IF NOT OBJECT_ID('tempdb.dbo.#OBJECTSRCs') IS NULL DROP TABLE #OBJECTSRCs
 IF NOT OBJECT_ID('tempdb.dbo.#STATS') IS NULL DROP TABLE #STATS
END --_CVP_Process
GO



IF NOT OBJECT_ID('dbo._CVP_IMPORT_TRC') IS NULL DROP PROCEDURE dbo._CVP_IMPORT_TRC
GO
CREATE PROCEDURE dbo._CVP_IMPORT_TRC(@lcTRC NVARCHAR(1000), @lcFOLDER NVARCHAR(1000), @lcSHORTFILENAME NVARCHAR(1000), @liMODE INT=1)
AS
BEGIN
 DECLARE @ltT1 DATETIME, @lcSQL VARCHAR(MAX)


 SET @ltT1=GETDATE()
 EXEC _CVP_Process @lcTRC , @lcFOLDER,  @lcSHORTFILENAME, @liMODE
 PRINT '_CVP_Process '+CAST(DATEDIFF(ms,@ltT1,GETDATE())/1000.0 AS VARCHAR(30))

 
 
END --_CVP_IMPORT_TRC
GO

IF NOT OBJECT_ID('dbo._CVP_COLSLIST') IS NULL DROP FUNCTION dbo._CVP_COLSLIST
GO
CREATE FUNCTION dbo._CVP_COLSLIST()
RETURNS  @loCOLS TABLE (COLID INT, COLNAME NVARCHAR(128), COLDESCR NVARCHAR(4000), TYPENAME NVARCHAR(128), PRIMARY KEY (COLID))
AS
BEGIN
 INSERT INTO @loCOLS VALUES (1,'TextData', 'Text value dependent on the event class that is captured in the trace.','ntext');
 INSERT INTO @loCols VALUES (2,'BinaryData', 'Binary value dependent on the event class captured in the trace.','image')
 INSERT INTO @loCols VALUES (3,'DatabaseID', 'ID of the database specified by the USE database statement, or the default database if no USE database statement is issued for a given connection. The value for a database can be determined by using the DB_ID function.','int')
 INSERT INTO @loCols VALUES (4,'TransactionID', 'System-assigned ID of the transaction.','bigint')
 INSERT INTO @loCols VALUES (5,'LineNumber', 'Contains the number of the line that contains the error. For events that involve Transact-SQL statements, like SP:StmtStarting, the LineNumber contains the line number of the statement in the stored procedure or batch.','int')
 INSERT INTO @loCols VALUES (6,'NTUserName', 'Microsoft Windows user name.','nvarchar')
 INSERT INTO @loCols VALUES (7,'NTDomainName', 'Windows domain to which the user belongs.','nvarchar')
 INSERT INTO @loCols VALUES (8,'HostName', 'Name of the client computer that originated the request.','nvarchar')
 INSERT INTO @loCols VALUES (9,'ClientProcessID', 'ID assigned by the client computer to the process in which the client application is running.','int')
 INSERT INTO @loCols VALUES (10,'ApplicationName', 'Name of the client application that created the connection to an instance of SQL Server. This column is populated with the values passed by the application rather than the displayed name of the program.','nvarchar')
 INSERT INTO @loCols VALUES (11,'LoginName', 'SQL Server login name of the client.','nvarchar')
 INSERT INTO @loCols VALUES (12,'SPID', 'Server Process ID assigned by SQL Server to the process associated with the client.','int')
 INSERT INTO @loCols VALUES (13,'Duration', 'Amount of elapsed time (in microseconds) taken by the event. This data column is not populated by the Hash Warning event.','bigint')
 INSERT INTO @loCols VALUES (14,'StartTime', 'Time at which the event started, when available.','datetime')
 INSERT INTO @loCols VALUES (15,'EndTime', 'Time at which the event ended. This column is not populated for starting event classes, such as SQL:BatchStarting or SP:Starting. It is also not populated by the Hash Warning event.','datetime')
 INSERT INTO @loCols VALUES (16,'Reads', 'Number of logical disk reads performed by the server on behalf of the event. This column is not populated by the Lock:Released event.','bigint')
 INSERT INTO @loCols VALUES (17,'Writes', 'Number of physical disk writes performed by the server on behalf of the event.','bigint')
 INSERT INTO @loCols VALUES (18,'CPU', 'Amount of CPU time (in milliseconds) used by the event.','int')
 INSERT INTO @loCols VALUES (19,'Permissions', 'Represents the bitmap of permissions; used by Security Auditing.','bigint')
 INSERT INTO @loCols VALUES (20,'Severity', 'Severity level of an exception.','int')
 INSERT INTO @loCols VALUES (21,'EventSubClass', 'Type of event subclass. This data column is not populated for all event classes.','int')
 INSERT INTO @loCols VALUES (22,'ObjectID', 'System-assigned ID of the object.','int')
 INSERT INTO @loCols VALUES (23,'Success', 'Success of the permissions usage attempt; used for auditing.'+CHAR(13)+CHAR(10)+'1 = success0 = failure','int')
 INSERT INTO @loCols VALUES (24,'IndexID', 'ID for the index on the object affected by the event. To determine the index ID for an object, use the indid column of the sysindexes system table.','int')
 INSERT INTO @loCols VALUES (25,'IntegerData', 'Integer value dependent on the event class captured in the trace.','int')
 INSERT INTO @loCols VALUES (26,'ServerName', 'Name of the instance of SQL Server, either servername or servername\instancename, being traced.','nvarchar')
 INSERT INTO @loCols VALUES (27,'EventClass', 'Type of event class being recorded.','int')
 INSERT INTO @loCols VALUES (28,'ObjectType', 'Type of object, such as: table, function, or stored procedure.','int')
 INSERT INTO @loCols VALUES (29,'NestLevel', 'The nesting level at which this stored procedure is executing. See @@NESTLEVEL (Transact-SQL).','int')
 INSERT INTO @loCols VALUES (30,'State', 'Server state, in case of an error.','int')
 INSERT INTO @loCols VALUES (31,'Error', 'Error number.','int')
 INSERT INTO @loCols VALUES (32,'Mode', 'Lock mode of the lock acquired. This column is not populated by the Lock:Released event.','int')
 INSERT INTO @loCols VALUES (33,'Handle', 'Handle of the object referenced in the event.','int')
 INSERT INTO @loCols VALUES (34,'ObjectName', 'Name of object accessed.','nvarchar')
 INSERT INTO @loCols VALUES (35,'DatabaseName', 'Name of the database specified in the USE database statement.','nvarchar')
 INSERT INTO @loCols VALUES (36,'FileName', 'Logical name of the file name modified.','nvarchar')
 INSERT INTO @loCols VALUES (37,'OwnerName', 'Owner name of the referenced object.','nvarchar')
 INSERT INTO @loCols VALUES (38,'RoleName', 'Name of the database or server-wide role targeted by a statement.','nvarchar')
 INSERT INTO @loCols VALUES (39,'TargetUserName', 'User name of the target of some action.','nvarchar')
 INSERT INTO @loCols VALUES (40,'DBUserName', 'SQL Server database user name of the client.','nvarchar')
 INSERT INTO @loCols VALUES (41,'LoginSid', 'Security identifier (SID) of the logged-in user.','image')
 INSERT INTO @loCols VALUES (42,'TargetLoginName', 'Login name of the target of some action.','nvarchar')
 INSERT INTO @loCols VALUES (43,'TargetLoginSid', 'SID of the login that is the target of some action.','image')
 INSERT INTO @loCols VALUES (44,'ColumnPermissions', 'Column-level permissions status; used by Security Auditing.','int')
 INSERT INTO @loCols VALUES (45,'LinkedServerName', 'Name of the linked server.','nvarchar')
 INSERT INTO @loCols VALUES (46,'ProviderName', 'Name of the OLE DB provider.','nvarchar')
 INSERT INTO @loCols VALUES (47,'MethodName', 'Name of the OLE DB method.','nvarchar')
 INSERT INTO @loCols VALUES (48,'RowCounts', 'Number of rows in the batch.','bigint')
 INSERT INTO @loCols VALUES (49,'RequestID', 'ID of the request containing the statement.','int')
 INSERT INTO @loCols VALUES (50,'XactSequence', 'A token to describe the current transaction.','bigint')
 INSERT INTO @loCols VALUES (51,'EventSequence', 'Sequence number for this event.','bigint')
 INSERT INTO @loCols VALUES (52,'BigintData1', 'bigint  value, which is dependent on the event class captured in the trace.','bigint')
 INSERT INTO @loCols VALUES (53,'BigintData2', 'bigint  value, which is dependent on the event class captured in the trace.','bigint')
 INSERT INTO @loCols VALUES (54,'GUID', 'GUID value, which is dependent on the event class captured in the trace.','uniqueidentifier')
 INSERT INTO @loCols VALUES (55,'IntegerData2', 'Integer value, which is dependent on the event class captured in the trace.','int')
 INSERT INTO @loCols VALUES (56,'ObjectID2', 'ID of the related object or entity, if available.','bigint')
 INSERT INTO @loCols VALUES (57,'Type', 'Integer value, which is dependent on the event class captured in the trace.','int')
 INSERT INTO @loCols VALUES (58,'OwnerID', 'Type of the object that owns the lock. For lock events only.','int')
 INSERT INTO @loCols VALUES (59,'ParentName', 'Name of the schema the object is within.','nvarchar')
 INSERT INTO @loCols VALUES (60,'IsSystem', 'Indicates whether the event occurred on a system process or a user process.'+CHAR(13)+CHAR(10)+'1 = system'+CHAR(13)+CHAR(10)+'0 = user.','int')
 INSERT INTO @loCols VALUES (61,'Offset', 'Starting offset of the statement within the stored procedure or batch.','int')
 INSERT INTO @loCols VALUES (62,'SourceDatabaseID', 'ID of the database in which the source of the object exists.','int')
 INSERT INTO @loCols VALUES (63,'SqlHandle', '64-bit hash based on the text of an ad hoc query or the database and object ID of an SQL object. This value can be passed to sys.dm_exec_sql_text() to retrieve the associated SQL text.','image')
 INSERT INTO @loCols VALUES (64,'SessionLoginName', 'The login name of the user who originated the session. For example, if you connect to SQL Server using Login1 and execute a statement as Login2, SessionLoginName displays Login1, while LoginName displays Login2. This data column displays both SQL Server and Windows logins.','nvarchar')
 INSERT INTO @loCols VALUES (65,'PlanHandle', '','image')
 INSERT INTO @loCols VALUES (66,'GroupID', '','int')

 RETURN
END --CVP_COLSLIST
GO

IF NOT OBJECT_ID('dbo._CVP_OBJTLIST') IS NULL DROP FUNCTION dbo._CVP_OBJTLIST
GO
CREATE FUNCTION dbo._CVP_OBJTLIST()
RETURNS  @loLIST TABLE (OBJECTTYPEID INT, OBJECTTYPENAME NVARCHAR(128), PRIMARY KEY (OBJECTTYPEID))
AS
BEGIN
 INSERT INTO @loLIST VALUES (8259,'Check Constraint');
 INSERT INTO @loLIST VALUES (8260,'Default (constraint or standalone)');
 INSERT INTO @loLIST VALUES (8262,'Foreign-key Constraint');
 INSERT INTO @loLIST VALUES (8272,'Stored Procedure');
 INSERT INTO @loLIST VALUES (8274,'Rule');
 INSERT INTO @loLIST VALUES (8275,'System Table');
 INSERT INTO @loLIST VALUES (8276,'Trigger on Server');
 INSERT INTO @loLIST VALUES (8277,'(User-defined) Table');
 INSERT INTO @loLIST VALUES (8278,'View');
 INSERT INTO @loLIST VALUES (8280,'Extended Stored Procedure');
 INSERT INTO @loLIST VALUES (16724,'CLR Trigger');
 INSERT INTO @loLIST VALUES (16964,'Database');
 INSERT INTO @loLIST VALUES (16975,'Object');
 INSERT INTO @loLIST VALUES (17222,'FullText Catalog');
 INSERT INTO @loLIST VALUES (17232,'CLR Stored Procedure');
 INSERT INTO @loLIST VALUES (17235,'Schema');
 INSERT INTO @loLIST VALUES (17475,'Credential');
 INSERT INTO @loLIST VALUES (17491,'DDL Event');
 INSERT INTO @loLIST VALUES (17741,'Management Event');
 INSERT INTO @loLIST VALUES (17747,'Security Event'); 
 INSERT INTO @loLIST VALUES (17749,'User Event');
 INSERT INTO @loLIST VALUES (17985,'CLR Aggregate Function');
 INSERT INTO @loLIST VALUES (17993,'Inline Table-valued SQL Function');
 INSERT INTO @loLIST VALUES (18000,'Partition Function'); 
 INSERT INTO @loLIST VALUES (18002,'Replication Filter Procedure');
 INSERT INTO @loLIST VALUES (18004,'Table-valued SQL Function');
 INSERT INTO @loLIST VALUES (18259,'Server Role');
 INSERT INTO @loLIST VALUES (18263,'Microsoft Windows Group');
 INSERT INTO @loLIST VALUES (19265,'Asymmetric Key');
 INSERT INTO @loLIST VALUES (19277,'Master Key');
 INSERT INTO @loLIST VALUES (19280,'Primary Key');
 INSERT INTO @loLIST VALUES (19283,'ObfusKey');
 INSERT INTO @loLIST VALUES (19521,'Asymmetric Key Login');
 INSERT INTO @loLIST VALUES (19523,'Certificate Login');
 INSERT INTO @loLIST VALUES (19538,'Role');
 INSERT INTO @loLIST VALUES (19539,'SQL Login');
 INSERT INTO @loLIST VALUES (19543,'Windows Login');
 INSERT INTO @loLIST VALUES (20034,'Remote Service Binding');
 INSERT INTO @loLIST VALUES (20036,'Event Notification on Database');
 INSERT INTO @loLIST VALUES (20037,'Event Notification');
 INSERT INTO @loLIST VALUES (20038,'Scalar SQL Function');
 INSERT INTO @loLIST VALUES (20047,'Event Notification on Object');
 INSERT INTO @loLIST VALUES (20051,'Synonym');
 INSERT INTO @loLIST VALUES (20307,'Sequence');
 INSERT INTO @loLIST VALUES (20549,'End Point');
 INSERT INTO @loLIST VALUES (20801,'Adhoc Queries which may be cached');
 INSERT INTO @loLIST VALUES (20816,'Prepared Queries which may be cached');
 INSERT INTO @loLIST VALUES (20819,'Service Broker Service Queue');
 INSERT INTO @loLIST VALUES (20821,'Unique Constraint');
 INSERT INTO @loLIST VALUES (21057,'Application Role');
 INSERT INTO @loLIST VALUES (21059,'Certificate');
 INSERT INTO @loLIST VALUES (21075,'Server');
 INSERT INTO @loLIST VALUES (21076,'Transact-SQL Trigger');
 INSERT INTO @loLIST VALUES (21313,'Assembly');
 INSERT INTO @loLIST VALUES (21318,'CLR Scalar Function');
 INSERT INTO @loLIST VALUES (21321,'Inline scalar SQL Function');
 INSERT INTO @loLIST VALUES (21328,'Partition Scheme');
 INSERT INTO @loLIST VALUES (21333,'User');
 INSERT INTO @loLIST VALUES (21571,'Service Broker Service Contract');
 INSERT INTO @loLIST VALUES (21572,'Trigger on Database');
 INSERT INTO @loLIST VALUES (21574,'CLR Table-valued Function');
 INSERT INTO @loLIST VALUES (21577,'Internal Table (For example, XML Node Table, Queue Table.)');
 INSERT INTO @loLIST VALUES (21581,'Service Broker Message Type');
 INSERT INTO @loLIST VALUES (21586,'Service Broker Route');
 INSERT INTO @loLIST VALUES (21587,'Statistics');
 INSERT INTO @loLIST VALUES (21825,'U1');
 INSERT INTO @loLIST VALUES (21827,'U2');
 INSERT INTO @loLIST VALUES (21831,'U3');
 INSERT INTO @loLIST VALUES (21843,'U4');
 INSERT INTO @loLIST VALUES (21847,'User');
 INSERT INTO @loLIST VALUES (22099,'Service Broker Service');
 INSERT INTO @loLIST VALUES (22601,'Index');
 INSERT INTO @loLIST VALUES (22604,'Certificate Login');
 INSERT INTO @loLIST VALUES (22611,'XMLSchema');
 INSERT INTO @loLIST VALUES (22868,'Type');

 RETURN
END --CVP_OBJTLIST
GO

IF NOT OBJECT_ID('dbo._CVP_EVENTSLIST') IS NULL DROP FUNCTION dbo._CVP_EVENTSLIST
GO
CREATE FUNCTION dbo._CVP_EVENTSLIST()
RETURNS @loLIST TABLE (ID INT, NAME NVARCHAR(128), DESCR NVARCHAR(MAX), PRIMARY KEY (ID))
AS
BEGIN

 INSERT INTO @loLIST VALUES (0 	,'Reserved 1','Reserved');
 INSERT INTO @loLIST VALUES (1  ,'Reserved 2','Reserved');
 INSERT INTO @loLIST VALUES (2  ,'Reserved 3','Reserved');
 INSERT INTO @loLIST VALUES (3  ,'Reserved 4','Reserved');
 INSERT INTO @loLIST VALUES (4  ,'Reserved 5','Reserved');
 INSERT INTO @loLIST VALUES (5  ,'Reserved 6','Reserved');
 INSERT INTO @loLIST VALUES (6  ,'Reserved 7','Reserved');
 INSERT INTO @loLIST VALUES (7  ,'Reserved 8','Reserved');
 INSERT INTO @loLIST VALUES (8  ,'Reserved 9','Reserved');
 INSERT INTO @loLIST VALUES (9  ,'Reserved 10','Reserved');
 INSERT INTO @loLIST VALUES (10	,'RPC:Completed','Occurs when a remote procedure call (RPC) has completed.');
 INSERT INTO @loLIST VALUES (11	,'RPC:Starting','Occurs when an RPC has started.');
 INSERT INTO @loLIST VALUES (12	,'SQL:BatchCompleted','Occurs when a Transact-SQL batch has completed.');
 INSERT INTO @loLIST VALUES (13	,'SQL:BatchStarting','Occurs when a Transact-SQL batch has started.');
 INSERT INTO @loLIST VALUES (14	,'Audit Login','Occurs when a user successfully logs in to SQL Server.');
 INSERT INTO @loLIST VALUES (15	,'Audit Logout','Occurs when a user logs out of SQL Server.');
 INSERT INTO @loLIST VALUES (16	,'Attention','Occurs when attention events, such as client-interrupt requests or broken client connections, happen.');
 INSERT INTO @loLIST VALUES (17	,'ExistingConnection','Detects all activity by users connected to SQL Server before the trace started.');
 INSERT INTO @loLIST VALUES (18	,'Audit Server Starts and Stops','Occurs when the SQL Server service state is modified.');
 INSERT INTO @loLIST VALUES (19	,'DTCTransaction','Tracks Microsoft Distributed Transaction Coordinator (MS DTC) coordinated transactions between two or more databases.');
 INSERT INTO @loLIST VALUES (20	,'Audit Login Failed','Indicates that a login attempt to SQL Server from a client failed.');
 INSERT INTO @loLIST VALUES (21 ,'EventLog','Indicates that events have been logged in the Windows application log.');
 INSERT INTO @loLIST VALUES (22 ,'ErrorLog','Indicates that error events have been logged in the SQL Server error log.');
 INSERT INTO @loLIST VALUES (23 ,'Lock:Released','Indicates that a lock on a resource, such as a page, has been released.');
 INSERT INTO @loLIST VALUES (24 ,'Lock:Acquired','Indicates acquisition of a lock on a resource, such as a data page.');
 INSERT INTO @loLIST VALUES (25 ,'Lock:Deadlock','Indicates that two concurrent transactions have deadlocked each other by trying to obtain incompatible locks on resources the other transaction owns. ');
 INSERT INTO @loLIST VALUES (26 ,'Lock:Cancel','Indicates that the acquisition of a lock on a resource has been canceled (for example, due to a deadlock).');
 INSERT INTO @loLIST VALUES (27 ,'Lock:Timeout','Indicates that a request for a lock on a resource, such as a page, has timed out due to another transaction holding a blocking lock on the required resource. Time-out is determined by the @@LOCK_TIMEOUT function, and can be set with the SET LOCK_TIMEOUT statement. ');
 INSERT INTO @loLIST VALUES (28 ,'Degree of Parallelism Event (7.0 Insert)','Occurs before a SELECT, INSERT, or UPDATE statement is executed. ');
 INSERT INTO @loLIST VALUES (29 ,'Reserved 29','Use Event 28 instead.');
 INSERT INTO @loLIST VALUES (30 ,'Reserved 30','Use Event 28 instead.');
 INSERT INTO @loLIST VALUES (31 ,'Reserved 31','Use Event 28 instead.');
 INSERT INTO @loLIST VALUES (32 ,'Reserved 32','Reserved');
 INSERT INTO @loLIST VALUES (33 ,'Exception','Indicates that an exception has occurred in SQL Server. ');
 INSERT INTO @loLIST VALUES (34 ,'SP:CacheMiss','Indicates when a stored procedure is not found in the procedure cache.');
 INSERT INTO @loLIST VALUES (35 ,'SP:CacheInsert','Indicates when an item is inserted into the procedure cache.');
 INSERT INTO @loLIST VALUES (36 ,'SP:CacheRemove','Indicates when an item is removed from the procedure cache.');
 INSERT INTO @loLIST VALUES (37 ,'SP:Recompile','Indicates that a stored procedure was recompiled.');
 INSERT INTO @loLIST VALUES (38 ,'SP:CacheHit','Indicates when a stored procedure is found in the procedure cache.');
 INSERT INTO @loLIST VALUES (39 ,'Deprecated','Deprecated');
 INSERT INTO @loLIST VALUES (40 ,'SQL:StmtStarting','Occurs when the Transact-SQL statement has started.');
 INSERT INTO @loLIST VALUES (41 ,'SQL:StmtCompleted','Occurs when the Transact-SQL statement has completed.');
 INSERT INTO @loLIST VALUES (42 ,'SP:Starting','Indicates when the stored procedure has started.');
 INSERT INTO @loLIST VALUES (43 ,'SP:Completed','Indicates when the stored procedure has completed.');
 INSERT INTO @loLIST VALUES (44 ,'SP:StmtStarting','Indicates that a Transact-SQL statement within a stored procedure has started executing.');
 INSERT INTO @loLIST VALUES (45 ,'SP:StmtCompleted','Indicates that a Transact-SQL statement within a stored procedure has finished executing.');
 INSERT INTO @loLIST VALUES (46 ,'Object:Created','Indicates that an object has been created, such as for CREATE INDEX, CREATE TABLE, and CREATE DATABASE statements.');
 INSERT INTO @loLIST VALUES (47 ,'Object:Deleted','Indicates that an object has been deleted, such as in DROP INDEX and DROP TABLE statements.');
 INSERT INTO @loLIST VALUES (48 ,'Reserved 48', NULL);
 INSERT INTO @loLIST VALUES (49 ,'Reserved 49', NULL);
 INSERT INTO @loLIST VALUES (50 ,'SQL Transaction','Tracks Transact-SQL BEGIN, COMMIT, SAVE, and ROLLBACK TRANSACTION statements.');
 INSERT INTO @loLIST VALUES (51 ,'Scan:Started','Indicates when a table or index scan has started.');
 INSERT INTO @loLIST VALUES (52 ,'Scan:Stopped','Indicates when a table or index scan has stopped.');
 INSERT INTO @loLIST VALUES (53 ,'CursorOpen','Indicates when a cursor is opened on a Transact-SQL statement by ODBC, OLE DB, or DB-Library.');
 INSERT INTO @loLIST VALUES (54 ,'TransactionLog','Tracks when transactions are written to the transaction log.');
 INSERT INTO @loLIST VALUES (55 ,'Hash Warning','Indicates that a hashing operation (for example, hash join, hash aggregate, hash union, and hash distinct) that is not processing on a buffer partition has reverted to an alternate plan. This can occur because of recursion depth, data skew, trace flags, or bit counting.');
 INSERT INTO @loLIST VALUES (56	,'Reserved 56',NULL);
 INSERT INTO @loLIST VALUES (57	,'Reserved 57',NULL);
 INSERT INTO @loLIST VALUES (58 ,'Auto Stats','Indicates an automatic updating of index statistics has occurred.');
 INSERT INTO @loLIST VALUES (59 ,'Lock:Deadlock Chain','Produced for each of the events leading up to the deadlock.');
 INSERT INTO @loLIST VALUES (60 ,'Lock:Escalation','Indicates that a finer-grained lock has been converted to a coarser-grained lock (for example, a page lock escalated or converted to a TABLE or HoBT lock).');
 INSERT INTO @loLIST VALUES (61 ,'OLE DB Errors','Indicates that an OLE DB error has occurred.');
 INSERT INTO @loLIST VALUES (62 ,'Reserved 62',NULL);
 INSERT INTO @loLIST VALUES (63	,'Reserved 63',NULL);
 INSERT INTO @loLIST VALUES (64	,'Reserved 64',NULL);
 INSERT INTO @loLIST VALUES (65	,'Reserved 65',NULL);
 INSERT INTO @loLIST VALUES (66 ,'Reserved 66',NULL);
 INSERT INTO @loLIST VALUES (67 ,'Execution Warnings','Indicates any warnings that occurred during the execution of a SQL Server statement or stored procedure.');
 INSERT INTO @loLIST VALUES (68 ,'Showplan Text (Unencoded)','Displays the plan tree of the Transact-SQL statement executed.');
 INSERT INTO @loLIST VALUES (69 ,'Sort Warnings','Indicates sort operations that do not fit into memory. Does not include sort operations involving the creating of indexes; only sort operations within a query (such as an ORDER BY clause used in a SELECT statement).');
 INSERT INTO @loLIST VALUES (70 ,'CursorPrepare','Indicates when a cursor on a Transact-SQL statement is prepared for use by ODBC, OLE DB, or DB-Library.');
 INSERT INTO @loLIST VALUES (71 ,'Prepare SQL','ODBC, OLE DB, or DB-Library has prepared a Transact-SQL statement or statements for use.');
 INSERT INTO @loLIST VALUES (72 ,'Exec Prepared SQL','ODBC, OLE DB, or DB-Library has executed a prepared Transact-SQL statement or statements.');
 INSERT INTO @loLIST VALUES (73 ,'Unprepare SQL','ODBC, OLE DB, or DB-Library has unprepared (deleted) a prepared Transact-SQL statement or statements.');
 INSERT INTO @loLIST VALUES (74 ,'CursorExecute','A cursor previously prepared on a Transact-SQL statement by ODBC, OLE DB, or DB-Library is executed.');
 INSERT INTO @loLIST VALUES (75 ,'CursorRecompile','A cursor opened on a Transact-SQL statement by ODBC or DB-Library has been recompiled either directly or due to a schema change. Triggered for ANSI and non-ANSI cursors.');
 INSERT INTO @loLIST VALUES (76 ,'CursorImplicitConversion','A cursor on a Transact-SQL statement is converted by SQL Server from one type to another. Triggered for ANSI and non-ANSI cursors.');
 INSERT INTO @loLIST VALUES (77 ,'CursorUnprepare','A prepared cursor on a Transact-SQL statement is unprepared (deleted) by ODBC, OLE DB, or DB-Library.');
 INSERT INTO @loLIST VALUES (78 ,'CursorClose','A cursor previously opened on a Transact-SQL statement by ODBC, OLE DB, or DB-Library is closed.');
 INSERT INTO @loLIST VALUES (79 ,'Missing Column Statistics','Column statistics that could have been useful for the optimizer are not available.');
 INSERT INTO @loLIST VALUES (80 ,'Missing Join Predicate','Query that has no join predicate is being executed. This could result in a long-running query.');
 INSERT INTO @loLIST VALUES (81 ,'Server Memory Change','SQL Server memory usage has increased or decreased by either 1 megabyte (MB) or 5 percent of the maximum server memory, whichever is greater.');
 INSERT INTO @loLIST VALUES (82 ,'User Configurable (0)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (83 ,'User Configurable (1)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (84	,'User Configurable (2)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (85 ,'User Configurable (3)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (86 ,'User Configurable (4)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (87	,'User Configurable (5)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (88 ,'User Configurable (6)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (89 ,'User Configurable (7)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (90	,'User Configurable (8)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (91 ,'User Configurable (9)	','Event data defined by the user.');
 INSERT INTO @loLIST VALUES (92 ,'Data File Auto Grow','Indicates that a data file was extended automatically by the server.');
 INSERT INTO @loLIST VALUES (93 ,'Log File Auto Grow','Indicates that a log file was extended automatically by the server.');
 INSERT INTO @loLIST VALUES (94 ,'Data File Auto Shrink','Indicates that a data file was shrunk automatically by the server.');
 INSERT INTO @loLIST VALUES (95 ,'Log File Auto Shrink','Indicates that a log file was shrunk automatically by the server.');
 INSERT INTO @loLIST VALUES (96 ,'Showplan Text','Displays the query plan tree of the SQL statement from the query optimizer. Note that the TextData column does not contain the Showplan for this event.');
 INSERT INTO @loLIST VALUES (97 ,'Showplan All','Displays the query plan with full compile-time details of the SQL statement executed. Note that the TextData column does not contain the Showplan for this event.');
 INSERT INTO @loLIST VALUES (98 ,'Showplan Statistics Profile','Displays the query plan with full run-time details of the SQL statement executed. Note that the TextData column does not contain the Showplan for this event.');
 INSERT INTO @loLIST VALUES (99 ,'Reserved',NULL);
 INSERT INTO @loLIST VALUES (100,'RPC Output Parameter','Produces output values of the parameters for every RPC.');
 INSERT INTO @loLIST VALUES (101,'Reserved', NULL);
 INSERT INTO @loLIST VALUES (102,'Audit Database Scope GDR','Occurs every time a GRANT, DENY, REVOKE for a statement permission is issued by any user in SQL Server for database-only actions such as granting permissions on a database.');
 INSERT INTO @loLIST VALUES (103,'Audit Object GDR Event','Occurs every time a GRANT, DENY, REVOKE for an object permission is issued by any user in SQL Server.');
 INSERT INTO @loLIST VALUES (104,'Audit AddLogin Event','Occurs when a SQL Server login is added or removed; for sp_addlogin and sp_droplogin.');
 INSERT INTO @loLIST VALUES (105,'Audit Login GDR Event','Occurs when a Windows login right is added or removed; for sp_grantlogin, sp_revokelogin, and sp_denylogin.');
 INSERT INTO @loLIST VALUES (106,'Audit Login Change Property Event','Occurs when a property of a login, except passwords, is modified; for sp_defaultdb and sp_defaultlanguage.');
 INSERT INTO @loLIST VALUES (107,'Audit Login Change Password Event','Occurs when a SQL Server login password is changed. Passwords are not recorded.');
 INSERT INTO @loLIST VALUES (108,'Audit Add Login to Server Role Event','Occurs when a login is added or removed from a fixed server role; for sp_addsrvrolemember, and sp_dropsrvrolemember.');
 INSERT INTO @loLIST VALUES (109,'Audit Add DB User Event','Occurs when a login is added or removed as a database user (Windows or SQL Server) to a database; for sp_grantdbaccess, sp_revokedbaccess, sp_adduser, and sp_dropuser.');
 INSERT INTO @loLIST VALUES (110,'Audit Add Member to DB Role Event','Occurs when a login is added or removed as a database user (fixed or user-defined) to a database; for sp_addrolemember, sp_droprolemember, and sp_changegroup.');
 INSERT INTO @loLIST VALUES (111,'Audit Add Role Event','Occurs when a login is added or removed as a database user to a database; for sp_addrole and sp_droprole.');
 INSERT INTO @loLIST VALUES (112,'Audit App Role Change Password Event','Occurs when a password of an application role is changed.');
 INSERT INTO @loLIST VALUES (113,'Audit Statement Permission Event','Occurs when a statement permission (such as CREATE TABLE) is used.');
 INSERT INTO @loLIST VALUES (114,'Audit Schema Object Access Event','Occurs when an object permission (such as SELECT) is used, both successfully or unsuccessfully.');
 INSERT INTO @loLIST VALUES (115,'Audit Backup/Restore Event','Occurs when a BACKUP or RESTORE command is issued.');
 INSERT INTO @loLIST VALUES (116,'Audit DBCC Event','Occurs when DBCC commands are issued.');
 INSERT INTO @loLIST VALUES (117,'Audit Change Audit Event','Occurs when audit trace modifications are made.');
 INSERT INTO @loLIST VALUES (118,'Audit Object Derived Permission Event','Occurs when a CREATE, ALTER, and DROP object commands are issued.');
 INSERT INTO @loLIST VALUES (119,'OLEDB Call Event','Occurs when OLE DB provider calls are made for distributed queries and remote stored procedures.');
 INSERT INTO @loLIST VALUES (120,'OLEDB QueryInterface Event','Occurs when OLE DB QueryInterface calls are made for distributed queries and remote stored procedures.');
 INSERT INTO @loLIST VALUES (121,'OLEDB DataRead Event','Occurs when a data request call is made to the OLE DB provider.');
 INSERT INTO @loLIST VALUES (122,'Showplan XML','Occurs when an SQL statement executes. Include this event to identify Showplan operators. Each event is stored in a well-formed XML document. Note that the Binary column for this event contains the encoded Showplan. Use SQL Server Profiler to open the trace and view the Showplan.');
 INSERT INTO @loLIST VALUES (123,'SQL:FullTextQuery','Occurs when a full text query executes.');
 INSERT INTO @loLIST VALUES (124,'Broker:Conversation','Reports the progress of a Service Broker conversation.');
 INSERT INTO @loLIST VALUES (125,'Deprecation Announcement','Occurs when you use a feature that will be removed from a future version of SQL Server.');
 INSERT INTO @loLIST VALUES (126,'Deprecation Final Support','Occurs when you use a feature that will be removed from the next major release of SQL Server.');
 INSERT INTO @loLIST VALUES (127,'Exchange Spill Event','Occurs when communication buffers in a parallel query plan have been temporarily written to the tempdb database.');
 INSERT INTO @loLIST VALUES (128,'Audit Database Management Event','Occurs when a database is created, altered, or dropped.');
 INSERT INTO @loLIST VALUES (129,'Audit Database Object Management Event','Occurs when a CREATE, ALTER, or DROP statement executes on database objects, such as schemas.');
 INSERT INTO @loLIST VALUES (130,'Audit Database Principal Management Event','Occurs when principals, such as users, are created, altered, or dropped from a database.');
 INSERT INTO @loLIST VALUES (131,'Audit Schema Object Management Event','Occurs when server objects are created, altered, or dropped.');
 INSERT INTO @loLIST VALUES (132,'Audit Server Principal Impersonation Event','Occurs when there is an impersonation within server scope, such as EXECUTE AS LOGIN.');
 INSERT INTO @loLIST VALUES (133,'Audit Database Principal Impersonation Event','Occurs when an impersonation occurs within the database scope, such as EXECUTE AS USER or SETUSER.');
 INSERT INTO @loLIST VALUES (134,'Audit Server Object Take Ownership Event','Occurs when the owner is changed for objects in server scope.');
 INSERT INTO @loLIST VALUES (135,'Audit Database Object Take Ownership Event','Occurs when a change of owner for objects within database scope occurs.');
 INSERT INTO @loLIST VALUES (136,'Broker:Conversation Group','Occurs when Service Broker creates a new conversation group or drops an existing conversation group.');
 INSERT INTO @loLIST VALUES (137,'Blocked Process Report','Occurs when a process has been blocked for more than a specified amount of time. Does not include system processes or processes that are waiting on non deadlock-detectable resources. Use sp_configure to configure the threshold and frequency at which reports are generated.');
 INSERT INTO @loLIST VALUES (138,'Broker:Connection','Reports the status of a transport connection managed by Service Broker.');
 INSERT INTO @loLIST VALUES (139,'Broker:Forwarded Message Sent','Occurs when Service Broker forwards a message.');
 INSERT INTO @loLIST VALUES (140,'Broker:Forwarded Message Dropped','Occurs when Service Broker drops a message that was intended to be forwarded.');
 INSERT INTO @loLIST VALUES (141,'Broker:Message Classify','Occurs when Service Broker determines the routing for a message.');
 INSERT INTO @loLIST VALUES (142,'Broker:Transmission','Indicates that errors have occurred in the Service Broker transport layer. The error number and state values indicate the source of the error.');
 INSERT INTO @loLIST VALUES (143,'Broker:Queue Disabled','Indicates a poison message was detected because there were five consecutive transaction rollbacks on a Service Broker queue. The event contains the database ID and queue ID of the queue that contains the poison message.');
 INSERT INTO @loLIST VALUES (144	,'Reserved 144',NULL);
 INSERT INTO @loLIST VALUES (145	,'Reserved 145',NULL);
 INSERT INTO @loLIST VALUES (146,'Showplan XML Statistics Profile','Occurs when an SQL statement executes. Identifies the Showplan operators and displays complete, compile-time data. Note that the Binary column for this event contains the encoded Showplan. Use SQL Server Profiler to open the trace and view the Showplan.');
 INSERT INTO @loLIST VALUES (148,'Deadlock Graph','Occurs when an attempt to acquire a lock is canceled because the attempt was part of a deadlock and was chosen as the deadlock victim. Provides an XML description of a deadlock.');
 INSERT INTO @loLIST VALUES (149,'Broker:Remote Message Acknowledgement','Occurs when Service Broker sends or receives a message acknowledgement.');
 INSERT INTO @loLIST VALUES (150,'Trace File Close','Occurs when a trace file closes during a trace file rollover.');
 INSERT INTO @loLIST VALUES (151,'Reserved',NULL);	
 INSERT INTO @loLIST VALUES (152,'Audit Change Database Owner','Occurs when ALTER AUTHORIZATION is used to change the owner of a database and permissions are checked to do that.');
 INSERT INTO @loLIST VALUES (153,'Audit Schema Object Take Ownership Event','Occurs when ALTER AUTHORIZATION is used to assign an owner to an object and permissions are checked to do that.');
 INSERT INTO @loLIST VALUES (154,'Reserved',NULL);
 INSERT INTO @loLIST VALUES (155,'FT:Crawl Started','Occurs when a full-text crawl (population) starts. Use to check if a crawl request is picked up by worker tasks.');
 INSERT INTO @loLIST VALUES (156,'FT:Crawl Stopped','Occurs when a full-text crawl (population) stops. Stops occur when a crawl completes successfully or when a fatal error occurs.');
 INSERT INTO @loLIST VALUES (157,'FT:Crawl Aborted','Occurs when an exception is encountered during a full-text crawl. Usually causes the full-text crawl to stop.');
 INSERT INTO @loLIST VALUES (158,'Audit Broker Conversation','Reports audit messages related to Service Broker dialog security.');
 INSERT INTO @loLIST VALUES (159,'Audit Broker Login','Reports audit messages related to Service Broker transport security.');
 INSERT INTO @loLIST VALUES (160,'Broker:Message Undeliverable','Occurs when Service Broker is unable to retain a received message that should have been delivered to a service.');
 INSERT INTO @loLIST VALUES (161,'Broker:Corrupted Message','Occurs when Service Broker receives a corrupted message.');
 INSERT INTO @loLIST VALUES (162,'User Error Message','Displays error messages that users see in the case of an error or exception.');
 INSERT INTO @loLIST VALUES (163,'Broker:Activation','Occurs when a queue monitor starts an activation stored procedure, sends a QUEUE_ACTIVATION notification, or when an activation stored procedure started by a queue monitor exits.');
 INSERT INTO @loLIST VALUES (164,'Object:Altered','Occurs when a database object is altered.');
 INSERT INTO @loLIST VALUES (165,'Performance statistics','Occurs when a compiled query plan has been cached for the first time, recompiled, or removed from the plan cache.');
 INSERT INTO @loLIST VALUES (166,'SQL:StmtRecompile','Occurs when a statement-level recompilation occurs.');
 INSERT INTO @loLIST VALUES (167,'Database Mirroring State Change','Occurs when the state of a mirrored database changes.');
 INSERT INTO @loLIST VALUES (168,'Showplan XML For Query Compile','Occurs when an SQL statement compiles. Displays the complete, compile-time data. Note that the Binary column for this event contains the encoded Showplan. Use SQL Server Profiler to open the trace and view the Showplan.');
 INSERT INTO @loLIST VALUES (169,'Showplan All For Query Compile','Occurs when an SQL statement compiles. Displays complete, compile-time data. Use to identify Showplan operators.');
 INSERT INTO @loLIST VALUES (170,'Audit Server Scope GDR Event','Indicates that a grant, deny, or revoke event for permissions in server scope occurred, such as creating a login.');
 INSERT INTO @loLIST VALUES (171,'Audit Server Object GDR Event','Indicates that a grant, deny, or revoke event for a schema object, such as a table or function, occurred.');
 INSERT INTO @loLIST VALUES (172,'Audit Database Object GDR Event','Indicates that a grant, deny, or revoke event for database objects, such as assemblies and schemas, occurred.');
 INSERT INTO @loLIST VALUES (173,'Audit Server Operation Event','Occurs when Security Audit operations such as altering settings, resources, external access, or authorization are used.');
 INSERT INTO @loLIST VALUES (175,'Audit Server Alter Trace Event','Occurs when a statement checks for the ALTER TRACE permission.');
 INSERT INTO @loLIST VALUES (176,'Audit Server Object Management Event','Occurs when server objects are created, altered, or dropped.');
 INSERT INTO @loLIST VALUES (177,'Audit Server Principal Management Event','Occurs when server principals are created, altered, or dropped.');
 INSERT INTO @loLIST VALUES (178,'Audit Database Operation Event','Occurs when database operations occur, such as checkpoint or subscribe query notification.');
 INSERT INTO @loLIST VALUES (180,'Audit Database Object Access Event','Occurs when database objects, such as schemas, are accessed.');
 INSERT INTO @loLIST VALUES (181,'TM: Begin Tran starting','Occurs when a BEGIN TRANSACTION request starts.');
 INSERT INTO @loLIST VALUES (182,'TM: Begin Tran completed','Occurs when a BEGIN TRANSACTION request completes.');
 INSERT INTO @loLIST VALUES (183,'TM: Promote Tran starting','Occurs when a PROMOTE TRANSACTION request starts.');
 INSERT INTO @loLIST VALUES (184,'TM: Promote Tran completed','Occurs when a PROMOTE TRANSACTION request completes.');
 INSERT INTO @loLIST VALUES (185,'TM: Commit Tran starting','Occurs when a COMMIT TRANSACTION request starts.');
 INSERT INTO @loLIST VALUES (186,'TM: Commit Tran completed','Occurs when a COMMIT TRANSACTION request completes.');
 INSERT INTO @loLIST VALUES (187,'TM: Rollback Tran starting','Occurs when a ROLLBACK TRANSACTION request starts.');
 INSERT INTO @loLIST VALUES (188,'TM: Rollback Tran completed','Occurs when a ROLLBACK TRANSACTION request completes.');
 INSERT INTO @loLIST VALUES (189,'Lock:Timeout (timeout > 0)','Occurs when a request for a lock on a resource, such as a page, times out.');
 INSERT INTO @loLIST VALUES (190,'Progress Report: Online Index Operation','Reports the progress of an online index build operation while the build process is running.');
 INSERT INTO @loLIST VALUES (191,'TM: Save Tran starting','Occurs when a SAVE TRANSACTION request starts.');
 INSERT INTO @loLIST VALUES (192,'TM: Save Tran completed','Occurs when a SAVE TRANSACTION request completes.');
 INSERT INTO @loLIST VALUES (193,'Background Job Error','Occurs when a background job terminates abnormally.');
 INSERT INTO @loLIST VALUES (194,'OLEDB Provider Information','Occurs when a distributed query runs and collects information corresponding to the provider connection.');
 INSERT INTO @loLIST VALUES (195,'Mount Tape','Occurs when a tape mount request is received.');
 INSERT INTO @loLIST VALUES (196,'Assembly Load','Occurs when a request to load a CLR assembly occurs.');
 INSERT INTO @loLIST VALUES (197,'Reserved 197', NULL);
 INSERT INTO @loLIST VALUES (198,'XQuery Static Type','Occurs when an XQuery expression is executed. This event class provides the static type of the XQuery expression.');
 INSERT INTO @loLIST VALUES (199,'QN: subscription','Occurs when a query registration cannot be subscribed. The TextData column contains information about the event.');
 INSERT INTO @loLIST VALUES (200,'QN: parameter table','Information about active subscriptions is stored in internal parameter tables. This event class occurs when a parameter table is created or deleted. Typically, these tables are created or deleted when the database is restarted. The TextData column contains information about the event.');
 INSERT INTO @loLIST VALUES (201,'QN: template','A query template represents a class of subscription queries. Typically, queries in the same class are identical except for their parameter values. This event class occurs when a new subscription request falls into an already existing class of (Match), a new class (Create), or a Drop class, which indicates cleanup of templates for query classes without active subscriptions. The TextData column contains information about the event.');
 INSERT INTO @loLIST VALUES (202,'QN: dynamics','Tracks internal activities of query notifications. The TextData column contains information about the event.');
 INSERT INTO @loLIST VALUES (212,'Bitmap Warning','Indicates when bitmap filters have been disabled in a query.');
 INSERT INTO @loLIST VALUES (213,'Database Suspect Data Page','Indicates when a page is added to the suspect_pages table in msdb.');
 INSERT INTO @loLIST VALUES (214,'CPU threshold exceeded','Indicates when the Resource Governor detects a query has exceeded the CPU threshold value (REQUEST_MAX_CPU_TIME_SEC).');
 INSERT INTO @loLIST VALUES (215,'Indicates when a LOGON trigger or Resource Governor classifier function starts execution.','Indicates when a LOGON trigger or Resource Governor classifier function starts execution.');
 INSERT INTO @loLIST VALUES (216,'PreConnect:Completed','Indicates when a LOGON trigger or Resource Governor classifier function completes execution.');
 INSERT INTO @loLIST VALUES (217,'Plan Guide Successful','Indicates that SQL Server successfully produced an execution plan for a query or batch that contained a plan guide.');
 INSERT INTO @loLIST VALUES (218,'Plan Guide Unsuccessful','Indicates that SQL Server could not produce an execution plan for a query or batch that contained a plan guide. SQL Server attempted to generate an execution plan for this query or batch without applying the plan guide. An invalid plan guide may be the cause of this problem. You can validate the plan guide by using the sys.fn_validate_plan_guide system function.');
 INSERT INTO @loLIST VALUES (235,'Audit Fulltext',NULL);

 RETURN
END --_CVP_EVENTSLIST
GO

IF NOT OBJECT_ID('dbo._CVP_STARTTRACE') IS NULL DROP PROCEDURE dbo._CVP_STARTTRACE
GO
CREATE PROCEDURE dbo._CVP_STARTTRACE(@litraceid INT)
AS
BEGIN
 -- Spuštění trace logu
 EXEC sp_trace_setstatus @litraceid, 1
END --_CVP_STARTTRACE
GO

IF NOT OBJECT_ID('dbo._CVP_PAUSETRACE') IS NULL DROP PROCEDURE dbo._CVP_PAUSETRACE
GO
CREATE PROCEDURE dbo._CVP_PAUSETRACE(@litraceid INT)
AS
BEGIN
 -- Pozastavení trace logu
 EXEC sp_trace_setstatus @litraceid, 0
END --_CVP_PAUSETRACE
GO

IF NOT OBJECT_ID('dbo._CVP_STOPTRACE') IS NULL DROP PROCEDURE dbo._CVP_STOPTRACE
GO
CREATE PROCEDURE dbo._CVP_STOPTRACE(@litraceid INT)
AS
BEGIN
 -- Zastavení trace logu
 EXEC sp_trace_setstatus @litraceid, 0
 -- Ukončení trace logu
 EXEC sp_trace_setstatus @litraceid, 2
 PRINT 'tracelog stop: '+CAST(@litraceid AS VARCHAR(30))

END --_CVP_STOPTRACE
GO

IF NOT OBJECT_ID('dbo._CVP_CREATETRACE') IS NULL DROP PROCEDURE dbo._CVP_CREATETRACE
GO
CREATE PROCEDURE dbo._CVP_CREATETRACE(@lcTRCFILE NVARCHAR(256), @lioptions INT=2, @liMAXFILESIZE BIGINT=1262485504, @litraceid INT OUT)
AS
BEGIN
 -- založení trace logu
 EXEC sp_trace_create @litraceid OUTPUT, @lioptions, @lcTRCFILE, @liMAXFILESIZE, NULL, NULL
 PRINT @litraceid
END --_CVP_CREATETRACE
GO

IF NOT OBJECT_ID('dbo._CVP_FILTERTRACE') IS NULL DROP PROCEDURE dbo._CVP_FILTERTRACE
GO
CREATE PROCEDURE dbo._CVP_FILTERTRACE(@litraceid INT, @lcLOPER VARCHAR(3), @lcCOL NVARCHAR(128), @lcCOPER VARCHAR(3), @luVAL SQL_VARIANT)
AS
BEGIN
 -- založení trace logu
 DECLARE @liLOPER INT, @liCOPER INT, @lcTYPENAME NVARCHAR(128), @liCOLID INT,
         @lbiVAL BIGINT, @ldVAL DATETIME, @lbVAL VARBINARY, @liVAL INT, @lcVAL NVARCHAR(512), @lgVAL UNIQUEIDENTIFIER

 SELECT @lcTYPENAME=TYPENAME, @liCOLID=COLID FROM dbo._CVP_COLSLIST() WHERE COLNAME=@lcCOL

 SET @liLOPER=CASE WHEN @lcLOPER='AND' OR @lcLOPER IS NULL THEN 0 ELSE 1 END
 SET @liCOPER=CASE @lcCOPER WHEN '=' THEN 0
                            WHEN '<>' THEN 1
                            WHEN '>' THEN 2
                            WHEN '<' THEN 3
                            WHEN '>=' THEN 4
                            WHEN '<=' THEN 5
                            WHEN 'LIKE' THEN 6  
                            WHEN 'NOT LIKE' THEN 7 ELSE 0 END

 IF @lcTYPENAME='bigint' BEGIN
    SET @lbiVAL=CAST( @luVal AS BIGINT)
    EXEC sp_trace_setfilter @litraceid, @liCOLID,  @liLOPER, @liCOPER, @lbiVAL
 END
 IF @lcTYPENAME='datetime' BEGIN
    SET @ldVAL=CAST( @luVal AS DATETIME)
    EXEC sp_trace_setfilter @litraceid, @liCOLID,  @liLOPER, @liCOPER, @ldVAL
 END
 IF @lcTYPENAME='image' BEGIN
    SET @lbVAL=CAST( @luVal AS VARBINARY(512))
    EXEC sp_trace_setfilter @litraceid, @liCOLID,  @liLOPER, @liCOPER, @lbVAL
 END
 IF @lcTYPENAME='int' BEGIN
    SET @liVAL=CAST( @luVal AS INT)
    EXEC sp_trace_setfilter @litraceid, @liCOLID,  @liLOPER, @liCOPER, @liVAL
 END
 IF @lcTYPENAME='ntext' BEGIN
    SET @lcVAL=CAST( @luVal AS NVARCHAR(512))
    EXEC sp_trace_setfilter @litraceid, @liCOLID,  @liLOPER, @liCOPER, @lcVAL
 END
 IF @lcTYPENAME='nvarchar' BEGIN
    SET @lcVAL=CAST( @luVal AS VARCHAR(512))
    EXEC sp_trace_setfilter @litraceid, @liCOLID,  @liLOPER, @liCOPER, @lcVAL
 END
 IF @lcTYPENAME='uniqueidentifier' BEGIN
    SET @lgVAL=CAST( @luVal AS UNIQUEIDENTIFIER)
    EXEC sp_trace_setfilter @litraceid, @liCOLID,  @liLOPER, @liCOPER, @lgVAL
 END

END --_CVP_FILTERTRACE
GO


IF NOT OBJECT_ID('dbo._CVP_QUICKTRACE') IS NULL DROP PROCEDURE dbo._CVP_QUICKTRACE
GO
CREATE PROCEDURE dbo._CVP_QUICKTRACE(@lcTRCFILE NVARCHAR(256), @litraceid INT OUT, @lcCOL NVARCHAR(128), @lcCOPER VARCHAR(3), @luVAL SQL_VARIANT, @lbDSQL BIT)
AS
BEGIN
 -- založení trace logu
 DECLARE @lioptions INT, @liMAXFILESIZE BIGINT, @liSET BIT
 SET @lioptions =2
 SET @liSET=1
 SET @liMAXFILESIZE=1024*1024*1024
 EXEC sp_trace_create @litraceid OUTPUT, @lioptions, @lcTRCFILE, @liMAXFILESIZE, NULL, NULL
 PRINT 'tracelog start: '+CAST(@litraceid AS VARCHAR(30))

    --SQL:StmtStarting
    EXEC sp_trace_setevent @litraceid, 40 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 40 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 40 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 40 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 40 , 49, @liSET --RequestID
    EXEC sp_trace_setevent @litraceid, 40 , 29, @liSET --NestLevel
    EXEC sp_trace_setevent @litraceid, 40 , 34, @liSET --Objectname
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 40 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 40 , 1, @liSET --TextData
    END

    --SQL:StmtCompleted
    EXEC sp_trace_setevent @litraceid, 41 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 41 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 41 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 41 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 41 , 49, @liSET --RequestID
    EXEC sp_trace_setevent @litraceid, 41 , 29, @liSET --NestLevel
    EXEC sp_trace_setevent @litraceid, 41 , 13, @liSET --Duration
    EXEC sp_trace_setevent @litraceid, 41 , 34, @liSET --Objectname
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 41 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 41 , 1, @liSET --TextData
    END

    --SP:Starting
    EXEC sp_trace_setevent @litraceid, 42 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 42 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 42 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 42 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 42 , 49, @liSET --RequestID
    EXEC sp_trace_setevent @litraceid, 42 , 29, @liSET --NestLevel
    EXEC sp_trace_setevent @litraceid, 42 , 34, @liSET --Objectname
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 42 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 42 , 1, @liSET --TextData
    END

    --SP:Completed
    EXEC sp_trace_setevent @litraceid, 43 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 43 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 43 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 43 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 43 , 49, @liSET --RequestID
    EXEC sp_trace_setevent @litraceid, 43 , 29, @liSET --NestLevel
    EXEC sp_trace_setevent @litraceid, 43 , 13, @liSET --Duration
    EXEC sp_trace_setevent @litraceid, 43 , 34, @liSET --Objectname
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 43 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 43 , 1, @liSET --TextData
    END

    --RPC:Starting
    EXEC sp_trace_setevent @litraceid, 11 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 11 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 11 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 11 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 11 , 34, @liSET --Objectname
    EXEC sp_trace_setevent @litraceid, 11 , 29, @liSET --NestLevel
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 11 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 11 , 1, @liSET --TextData
    END

    --RPC:Completed
    EXEC sp_trace_setevent @litraceid, 10 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 10 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 10 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 10 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 10 , 34, @liSET --Objectname
    EXEC sp_trace_setevent @litraceid, 10 , 29, @liSET --NestLevel
    EXEC sp_trace_setevent @litraceid, 10 , 13, @liSET --Duration
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 10 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 10 , 1, @liSET --TextData
    END

    --SQL:BatchStarting
    EXEC sp_trace_setevent @litraceid, 13 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 13 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 13 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 13 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 13 , 49, @liSET --RequestID
    EXEC sp_trace_setevent @litraceid, 13 , 29, @liSET --NestLevel
    EXEC sp_trace_setevent @litraceid, 13 , 34, @liSET --Objectname
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 13 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 13 , 1, @liSET --TextData
    END

    --SQL:BatchCompleted
    EXEC sp_trace_setevent @litraceid, 12 , 12, @liSET --SPID
    EXEC sp_trace_setevent @litraceid, 12 , 51, @liSET --EventSequence
    EXEC sp_trace_setevent @litraceid, 12 , 3, @liSET --DatabaseID
    EXEC sp_trace_setevent @litraceid, 12 , 22, @liSET --ObjectID
    EXEC sp_trace_setevent @litraceid, 12 , 49, @liSET --RequestID
    EXEC sp_trace_setevent @litraceid, 12 , 29, @liSET --NestLevel
    EXEC sp_trace_setevent @litraceid, 12 , 13, @liSET --Duration
    EXEC sp_trace_setevent @litraceid, 12 , 34, @liSET --Objectname
    IF @lbDSQL=1 BEGIN
       EXEC sp_trace_setevent @litraceid, 12 , 28, @liSET --ObjectType
       EXEC sp_trace_setevent @litraceid, 12 , 1, @liSET --TextData
    END


--SP:StmtStarting
 EXEC sp_trace_setevent @litraceid, 44 , 12, @liSET --SPID
 EXEC sp_trace_setevent @litraceid, 44 , 51, @liSET --EventSequence
 EXEC sp_trace_setevent @litraceid, 44 , 3, @liSET --DatabaseID
 EXEC sp_trace_setevent @litraceid, 44 , 22, @liSET --ObjectID
 EXEC sp_trace_setevent @litraceid, 44 , 61, @liSET --Offset
 EXEC sp_trace_setevent @litraceid, 44 , 5, @liSET --LineNumber
 EXEC sp_trace_setevent @litraceid, 44 , 29, @liSET --NestLevel
 EXEC sp_trace_setevent @litraceid, 44 , 49, @liSET --RequestID
 EXEC sp_trace_setevent @litraceid, 44 , 30, @liSET --State
 EXEC sp_trace_setevent @litraceid, 44 , 34, @liSET --Objectname
 IF @lbDSQL=1 BEGIN
    EXEC sp_trace_setevent @litraceid, 44 , 28, @liSET --ObjectType
    EXEC sp_trace_setevent @litraceid, 44 , 1, @liSET --TextData
 END

--SP:StmtCompleted
 EXEC sp_trace_setevent @litraceid, 45 , 12, @liSET --SPID
 EXEC sp_trace_setevent @litraceid, 45 , 51, @liSET --EventSequence
 EXEC sp_trace_setevent @litraceid, 45 , 3, @liSET --DatabaseID
 EXEC sp_trace_setevent @litraceid, 45 , 22, @liSET --ObjectID
 EXEC sp_trace_setevent @litraceid, 45 , 61, @liSET --Offset
 EXEC sp_trace_setevent @litraceid, 45 , 5, @liSET --LineNumber
 EXEC sp_trace_setevent @litraceid, 45 , 29, @liSET --NestLevel
 EXEC sp_trace_setevent @litraceid, 45 , 13, @liSET --Duration
 EXEC sp_trace_setevent @litraceid, 45 , 49, @liSET --RequestID
 EXEC sp_trace_setevent @litraceid, 45 , 30, @liSET --State
 EXEC sp_trace_setevent @litraceid, 45 , 34, @liSET --Objectname
 IF @lbDSQL=1 BEGIN
    EXEC sp_trace_setevent @litraceid, 45 , 28, @liSET --ObjectType
    --EXEC sp_trace_setevent @litraceid, 45 , 1, @liSET --TextData
 END

 EXEC dbo._CVP_FILTERTRACE @litraceid, NULL, @lcCOL, @lcCOPER, @luVAL
 IF @lbDSQL=0 BEGIN
    EXEC dbo._CVP_FILTERTRACE @litraceid, 'AND', 'ObjectType', '<>', 20801
    EXEC dbo._CVP_FILTERTRACE @litraceid, 'AND', 'ObjectType', '<>', 20816
 END

 -- Spuštění trace logu
 EXEC sp_trace_setstatus @litraceid, 1
END --_CVP_QUICKTRACE
GO





/*
exec dbo._CVP_CHECKGRANT


EXEC dbo._CVP_QUICKTRACE '\\server\MSPROFILER\TRC\IFPEUC02_007', NULL, 'SPID', '=', 58,0 -- without dynamic SQL
EXEC dbo._CVP_QUICKTRACE '\\server\MSPROFILER\TRC\IFPEUC02_007', NULL, 'SPID', '=', 58,1 -- with dynamic SQL

EXEC dbo._CVP_STOPTRACE 2

EXEC _CVP_IMPORT_TRC '\\server\MSPROFILER\TRC\IFPEUC02_007.trc', '\\server\MSPROFILER\log\', 'IFPEUC02_007',2

*/

