Query to get details of blocking and deadloack recorded in a table

Hi,
    whenever any blocking or deadlock occur in the server i have to record that information in a table with the query which is causing the locks with the login name.. Any query for this?

Blocking
For example, a 200-second blocked process threshold can
 be configured in SQL Server Management Studio as follows:
1.
 Execute Sp_configure ‘blocked process threshold’, 200  
2.
 RECONFIGURE WITH OVERRIDE;
Once the blocked process threshold is established, the next step is 
to capture the trace event. The trace events of blocking events that 
exceed the user configured threshold can be captured with SQL Trace or Profiler. 
3.
 If using SQL Trace, use sp_trace_setevent and event_id=137. 
4.
 If using SQL Server Profiler, select the Blocked Process Report event 
class (under the Errors and Warnings object).
Blocking per object with sys.dm_db_index_operational_stats
The new SQL Server 2005 DMV Sys.dm_db_index_operational_stats 
select top 10 * 
from sys.dm_os_wait_stats  
order by wait_time_ms desc
Deadlocks
Prerequisites : Please note that you must have Database Mail configured, 
SQL Server Agent must have the correct Alert System Configurations set to utilize this method and 
Traceflag 1222 must be on (DBCC TRACEON(1222, -1).
To make this work, first you will need to create the stored procedure that performs 
several steps, which are outlined below. Run this script to create the stored procedure:
CREATE PROC dbo.usp_DeadlockNotification
AS
DECLARE @NumOfDeadLocks int
SELECT @NumOfDeadLocks = SUM(cntr_value)
FROM sys.dm_os_performance_counters 
WHERE counter_name like '%dead%'
SET NOCOUNT ON
IF(@NumOfDeadLocks > 0)
BEGIN
  EXEC msdb.dbo.sp_send_dbmail
 @profile_name = 'SQLTestCluster',
 @recipients = '[email protected]',
 @subject = 'Deadlocks',
 @body = 'Please check errorlog for Deadlocks'
END
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • Query to get details of CollaboratorName and his Score in RFx Scoring

    Hi Experts,
    I m writing a query to get the scores given by collaborators in RFx Scoring.I got a report "RFx Response Analysis", where we can get the details of questions and the scores given by vendors to that questions.I m trying to get the details of Collaborators and the scores given by them in the below order.But i m facing problem to get details of Score given by collaborator.
    | Question |  Response | SupplierName |  CollaboratorName | ScoreByCollaborator |          
    Any turn arounds or ideas wud be gr8!
    Regards,
    Uday

    Hi Uday,
    Please let me know, how we can get Vendors scores and collobarators scores from the query.
    Thanks in advance
    Regards
    Natarajan

  • Query to get the details of Blocking and deadlock occurred for the Day

    Hi,
       I need a query to get the details of blocking and deadlock occurred for the day.

    You havent specified which version of SQL you are using which makes it difficult to give a solution. Assuming its latest versions , by default SQL Server (in any versions) doesnt track blocking information.
    You need to run some kind of queries/traces to capture blocking. The same goes with Deadlocks where majority of the DBA's enable trace flag 1222/1205 when they suspect deadlocks happening.
    Check this link -
    http://dba.stackexchange.com/questions/10644/deadlock-error-isnt-returning-the-deadlock-sql/10646#10646
    This link gives code to get historic deadlock information. I havent used it , I just googled to get that.
    That being said if you are looking for something to capture for the future check the below links.
    Check these links on how to setup extended events to capture deadlock and blocking.
    http://sqlblog.com/blogs/jonathan_kehayias/archive/2010/12/21/an-xevent-a-day-21-of-31-the-future-tracking-blocking-in-denali.aspx
    http://blogs.msdn.com/b/sqlserverfaq/archive/2013/04/27/an-in-depth-look-at-sql-server-memory-part-2.aspx
    http://blogs.technet.com/b/mspfe/archive/2012/06/28/how_2d00_to_2d00_monitor_2d00_deadlocks_2d00_in_2d00_sql_2d00_server.aspx
    HTH
    Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

  • SQL Query to get All AD Groups and its users in Active Directory

    Hi,
       Is there any query to get all AD groups and its user in an instance of a SQL server?

    Check this blog.
    http://www.mikefal.net/2011/04/18/monday-scripts-%E2%80%93-xp_logininfo/
    It will give you more than what is required. If you dont want the extra information,then you can try this.. I took the query and removed the bits that you might not require.
    declare @winlogins table
    (acct_name sysname,
    acct_type varchar(10),
    act_priv varchar(10),
    login_name sysname,
    perm_path sysname)
    declare @group sysname
    declare recscan cursor for
    select name from sys.server_principals
    where type = 'G' and name not like 'NT%'
    open recscan
    fetch next from recscan into @group
    while @@FETCH_STATUS = 0
    begin
    insert into @winlogins
    exec xp_logininfo @group,'members'
    fetch next from recscan into @group
    end
    close recscan
    deallocate recscan
    select
    u.name,
    u.type_desc,
    wl.login_name,
    wl.acct_type
    from sys.server_principals u
    inner join @winlogins wl on u.name = wl.perm_path
    where u.type = 'G'
    order by u.name,wl.login_name
    Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

  • Query to get holidays including saturday and sunday by giving month and year as input

    query to get holidays including saturday and sunday by giving month and year as input.

    Hi,
    Create a table for holidays.  You could INSERT one row for each holiday in each year, but it might be more useful if you just create 1 row for every day, with a column that tells whether that day is a holday, part of a weekend, or a work day.
    See
    http://forums.oracle.com/forums/message.jspa?messageID=3351081
    for a user-defined function that tests if a given DATE is holiday.
    You could use such a function when populating the table I mentioned earlier.

  • How to write customer exit in my BI query to get (current fiscal quarter) and (current fiscal quarter - 1 ) without user input

    Hi all,
    I need your help how to write customer exit in my BI query to get (current fiscal quarter) and (current fiscal quarter - 1 ) without user input.
    in my query info object is 0CALQUARTER and variable is ZFIS_QTR.
    in 0CALQUARTER fiscal quarter stored in 201301,201302,201303,201304 and 201401 format, for current fiscal quarter 201401 and (current fiscal quarter - 1 ) would be 201304.
    please replay ASAP to deliver the report to client.
    thanks in advance.
    -- Rakesh Nagpure

    I am Getting the same error for both the codes that i have written...
    Do i Need to write sth else in the code...
    Code:
    WHEN 'ZVLIVELEASES'.
      IF I_STEP = 2.
            L_DATE = SY-DATUM.
            SELECT * FROM "DSO_ACTIVE_TABLE"
                INTO TABLE ITAB_LL where "EXPIRY_DATE" > L_DATE.
            LOOP AT ITAB_LL INTO WA_LL.
            CLEAR l_s_range.
            l_s_range-sign = 'I'.
            l_s_range-opt = 'EQ'.
            l_s_range-low = WA_LL-"EXPIRY_DATE".
           APPEND L_S_RANGE TO E_T_RANGE.
            ENDLOOP.
       ENDIF.
    Error: Error for variable in customer enhancement ZLIVELEASES

  • Query to get all ports assigned and used by EBS instance.

    Hi,
    Can some one pleaase help to get
    Query to get all ports assigned and used by EBS instance.
    Help is appreaciated.
    Regards,
    Milan

    MILAN RATHOD wrote:
    Hi,
    Can some one pleaase help to get
    Query to get all ports assigned and used by EBS instance.
    Help is appreaciated.
    Regards,
    MilanIn addition to the thread referenced above by Helios, please check the context files and (Oracle E-Business Suite R12 Configuration in a DMZ [ID 380490.1] -- F. List of Ports to Open in a DMZ Configuration).
    Thanks,
    Hussein

  • SQL Query to get Project Plan Name and Resource Name from Reporting database of Project Server 2007

    Can you please help me to write an SQL Query to get Project Plan Name and Resource Name from Reporting database of Project Server 2007. Thanks!!

    Refer
    http://gallery.technet.microsoft.com/projectserver/Server-20072010-SQL-Get-a99d4bc6
    SELECT
    dbo.MSP_EpmAssignment_UserView.ProjectUID,
    dbo.MSP_EpmAssignment_UserView.TaskUID,
    dbo.MSP_EpmProject_UserView.ProjectName,
    dbo.MSP_EpmTask_UserView.TaskName,
    dbo.MSP_EpmAssignment_UserView.ResourceUID,
    dbo.MSP_EpmResource_UserView.ResourceName,
    dbo.MSP_EpmResource_UserView.ResourceInitials
    INTO #TempTable
    FROM dbo.MSP_EpmAssignment_UserView INNER JOIN
    dbo.MSP_EpmProject_UserView ON dbo.MSP_EpmAssignment_UserView.ProjectUID = dbo.MSP_EpmProject_UserView.ProjectUID INNER JOIN
    dbo.MSP_EpmTask_UserView ON dbo.MSP_EpmAssignment_UserView.TaskUID = dbo.MSP_EpmTask_UserView.TaskUID INNER JOIN
    dbo.MSP_EpmResource_UserView ON dbo.MSP_EpmAssignment_UserView.ResourceUID = dbo.MSP_EpmResource_UserView.ResourceUID
    SELECT
    ProjectUID,
    TaskUID,
    ProjectName,
    TaskName,
    STUFF((
    SELECT ', ' + ResourceInitials
    FROM #TempTable
    WHERE (TaskUID = Results.TaskUID)
    FOR XML PATH (''))
    ,1,2,'') AS ResourceInitialsCombined,
    STUFF((
    SELECT ', ' + ResourceName
    FROM #TempTable
    WHERE (TaskUID = Results.TaskUID)
    FOR XML PATH (''))
    ,1,2,'') AS ResourceNameCombined
    FROM #TempTable Results
    GROUP BY TaskUID,ProjectUID,ProjectName,TaskName
    DROP TABLE #TempTable
    -Prashanth

  • Query to get the data of all the columns in a table except any one column

    Can anyone please tell how to write a query to get the data of all the columns in a table except one particular column..
    For Example:
    Let us consider the EMP table.,
    From this table except the column comm all the remaining columns of the table should be listed
    For this we can write a query like this..
    Select empno, ename, job, mgr, sal, hiredate, deptno from emp;
    Just to avoid only one column, I mentioned all the remaining ( 7 ) columns of the table in the query..
    As the EMP table consists only 8 columns, it doesn't seem much difficult to mention all the columns in the query,
    but if a table have 100 columns in the table, then do we have to mention all the columns in the query..?
    Is there any other way of writing the query to get the required result..?
    Thanks..

    Your best best it to just list all the columns. Any other method will just cause more headaches and complicated code.
    If you really need to list all the columns for a table because you don't want to type them, just use something like...
    SQL> ed
    Wrote file afiedt.buf
      1  select trim(',' from sys_connect_by_path(column_name,',')) as columns
      2  from (select column_name, row_number() over (order by column_id) as column_id
      3        from user_tab_cols
      4        where column_name not in ('COMM')
      5        and   table_name = 'EMP'
      6       )
      7  where connect_by_isleaf = 1
      8  connect by column_id = prior column_id + 1
      9* start with column_id = 1
    SQL> /
    COLUMNS
    EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,DEPTNO
    SQL>

  • Query to get Primary ship to and bill to contact details

    Hi ,
    Please help me to get the query to find primary ship to and bill to contact details for a istore customer .
    Thanks
    Mark

    Hi Mark,
    The following should give you a good starting point.
    Regards,
    Jon
    SELECT
    cac_party.party_name as customer
    , cac.account_number
    , cac_party.party_number as orgnum
    , party_site.party_site_number as sitenum
    , csu.location
    , loc.address1
    , csu.site_use_code
    , orgcon.title
    , cont_party.party_name as contact_name
    , orgcon.job_title
    FROM
    hz_org_contacts orgcon
    , hz_party_relationships party_rel
    , hz_party_sites party_site
    , hz_cust_acct_sites_all cas
    , hz_cust_site_uses_all csu
    , hz_cust_accounts cac
    , hz_loc_assignments loc_assign
    , hz_locations loc
    , hz_parties cac_party
    , hz_parties cont_party
    WHERE 1=1
    AND orgcon.party_relationship_id = party_rel.party_relationship_id
    AND orgcon.party_site_id = party_site.party_site_id
    AND party_site.party_site_id = cas.party_site_id
    AND cas.cust_acct_site_id = csu.cust_acct_site_id
    AND cas.cust_account_id = cac.cust_account_id
    AND cac.party_id = cac_party.party_id
    AND cas.party_site_id = party_site.party_site_id
    AND loc.location_id = party_site.location_id
    AND loc.location_id = loc_assign.location_id
    AND party_rel.subject_id = cont_party.party_id AND cont_party.party_type = 'PERSON'
    ORDER BY cac_party.party_name, loc.address1, csu.site_use_code, cont_party.party_name

  • Query to get the Excise amount and basic amount based on the cst or vat tax

    Dear all,
                       I need a right query to get the basic amount ,excise amount and the tax amount based on the CST or VAT tax rate.The output should be like this,
    VAT
    goods excisabe at 1% - taxable amt(basic+excise for vat 1%)            tax amt
    goods excisable at 4%-   txable amt                                                       tax amt
    CST
    goods excisabe at 1% - taxable amt(basic+excise for CST 1%)            tax amt
    My problem will also be solved..if i am able to get  the basic value from base table OPCH itself............Since am using the PCH1 table to get the total basic amt...the values are duplicating.
    Regards,
    Shyam

    Hi Sowjanya,
    If you're simply trying to place a grand total, use the 'Insert Summary' option.
    Choose the measure field as the 'Field to Summarize' > Choose 'Sum' as the summary operation > Under 'Summary Location' choose 'Grand Total Report Footer'.
    -Abhilash

  • Query to get details from Maintenance plans

    Hi All,
    Could some one please let me know, if there is any way to check whether
    all  databases option is selected under the maintenance plan other than using GUI. Below is the print screen for reference.
    Maintenance plan includes rebuild Index, checkdb and  update statistics steps, I have to check whether the All databases option is selected for each individual task.
    I have a requirement wherein, I have to check this thing on around 5000 servers.
    It would be great if someone lets me know the script to check this setting, so that it will save my time.
    I have used below queries and tables to get the data, but they don't have the information which i'm looking for
     sysdbmaintplan_databases
    Contains one row for each database that has an associated upgraded database maintenance plan.
    sysdbmaintplan_history
        Contains one row for each upgraded database maintenance plan action performed.
    sysdbmaintplan_jobs
        Contains one row for each upgraded database maintenance plan job.
    sysdbmaintplans
        Contains one row for each upgraded database maintenance plan
        select * from sysdbmaintplan_jobs
        SELECT name,subplan_name,subplan_description
        FROM msdb.dbo.sysmaintplan_plans AS s
        INNER JOIN msdb.dbo.sysmaintplan_subplans AS sp ON sp.plan_id=s.id
        Order by name,subplan_name
     SELECT s.name AS MaintenancePlanName,
    sp.subplan_name AS SubplanName,
    subplan_description AS SubplanDescription,
    sj.name AS JobName,
    sj.enabled AS JobStatus,
    ss.name AS ScheduleName
    FROM msdb.dbo.sysmaintplan_plans AS s
    LEFT JOIN msdb.dbo.sysmaintplan_subplans AS sp ON sp.plan_id = s.id
    LEFT JOIN msdb.dbo.sysjobs AS sj ON sj.job_id = sp.job_id
    LEFT JOIN msdb.dbo.sysschedules AS ss ON sp.schedule_id = ss.schedule_id
    ORDER BY s.name,
    sp.subplan_name
    Thanks in Advance.
    Regards, Kranthi

    On a different note,  i think you can script the maintenance plan - ssis package and then insert into sysssiscatalog table and i think this will create the ssis - maintenance plan on the server. not sure ..this is just thought.... they can be compatibility
    issue.
    also, you can use the history - maintenance plans to get the data you need. but the caveat is the maintenance plan should have and history should exist and 'extended log  information' must be checked on the plan. this can be done - checking a text box
     in the plan properties.
    try this query.. i used top 1 ..so, you can try... if all databases are used in the plan..it will just show all  but if only some are used, i split that into multiple rows,(you might not need this)..there are some many other combinations possible,,
    such selecting on some tables etc...  you can query all that information from history tables, 
    try this query 
    use msdb
    go
    select top 1 @@SERVERNAME [servername],case when d.Succeeded=1 then 'Success' when d.succeeded=0 then 'Failed' End as Result,
    name,b.subplan_name,D.line1,D.line2,replace(D.line3,'Databases: ','') as [DBs],D.line4,D.line5,D.start_time,D.end_time,D.command,d.Succeeded
    into #test
    from sysmaintplan_plans a inner join sysmaintplan_subplans b on a.id=b.plan_id
    inner join sysmaintplan_log c on c.plan_id=b.plan_id and c.Subplan_id=b.subplan_id
    inner join sysmaintplan_logdetail d on d.task_detail_id=c.task_detail_id
    ORDER BY D.start_time DESC
    GO
    SELECT [ServerName],name,subplan_name,line2,
    Split.a.value('.', 'VARCHAR(100)') AS String
    FROM (SELECT [ServerName],name,subplan_name,line2,
    CAST ('<M>' + REPLACE([DBs], ',', '</M><M>') + '</M>' AS XML) AS Dbs
    FROM #test) AS A CROSS APPLY Dbs.nodes ('/M') AS Split(a);
    drop table #test
    anyways, on a side note, if you really have 5000 sql servers, you should looking at some tool or scripts to do this maintanence tasks than the builtin maintenance tasks as they provide better managebility. also, it is highly likely that you have multiple version,
    which makes it even harder to script out....
    Hope it Helps!!

  • Filemaker-how to match and flag records in two tables

    Hello,
    Tiger.8
    Filemaker Pro 8.5 Advanced
    I have two related tables in an FMP file.
    Table A has ~300 records, B ~2,000.
    Each record in A is unique for sure; I believe each one in B is unique.
    The goal is to determine whether any of the records in B match one in A based upon student ID.
    These IDs are like social security numbers; i.e., they are preassigned, unique 9-character values rather than ones that I'm assigning within FMP.
    Like SSNs, these IDs are unique. So within Table A, each ID is unique. Likewise, within B the IDs are unique.
    However, some IDs in A might also be in B. I need to find out programmatically which ones, if any, are in both tables.
    If a match exists, I need to flag a field in each table.
    I found and modified an AppleScript that someone else wrote.
    The original is as follows.
    tell application "FileMaker Pro"
    activate
    show every record of database "Original Database"
    show every record of database "Old Database"
    set field "Match" of document "Original Database" to ""
    set orgList to field "Full Name" of document "Original Database"
    set oldList to field "Full Name" of document "Old Database"
    set matchList to field "Match" of document "Original Database"
    repeat with i from 1 to (count of orgList)
    if oldList contains item i of orgList then
    set item i of matchList to "Match"
    end if
    end repeat
    set field "Match" of document "Original Database" to matchList
    show (every record of database "Original Database" whose cell "Match" = "Match")
    sort layout 2 of document "Original Database" by field "Last Name"
    show layout 2 of document "Old Database"
    end tell
    My revision is as follows.
    tell application "FileMaker Pro Advanced"
    activate
    show every record of table "A" of document "test"
    show every record of table "B" of document "test"
    set field "flag" of table "A" of document "test" to ""
    set field "flag" of table "B" of document "test" to ""
    set AList to field "ID" of table "A" of document "test"
    set BList to field "ID" of table "B" of document "test"
    set flagList to field "flag" of table "A" of document "test"
    repeat with i from 1 to (count of AList)
    if BList contains item i of AList then
    set item i of flagList to "flag"
    end if
    end repeat
    set field "flag" of table "A" of document "test" to flagList
    set field "flag" of table "B" of document "test" to flagList
    show (every record of database "test" whose cell "flag" = "flag")
    sort layout 1 of document "test" by field "ID"
    show layout 1 of document "test"
    end tell
    I sort of understand what each of the above commands does, but would appreciate answers to the following questions.
    1. How come a test record that I created in A and B that has bogus ID 1234 does not get flagged by the above revised script, but other records with valid matching IDs in both A and B do get flagged?
    2. How come all records in A that got flagged by the revised script do have counterparts in B, but only some of the ones in B that have a match in A got flagged?
    3. How do the commands "set Alist" and "set Blist" function?
    4. How do I fix the revised script so that it properly, correctly matches IDs between A and B, then properly, correctly flags the records in A and B that have matching IDs?
    Many thanks in advance and happy weekend!
    G4/1.25 MDD   Mac OS X (10.4.8)  

    >
    as there any way find out using comparison same records in two tables..........
    >
    >
    if i write a query then i can easily understand the same data is existed in two tables
    >
    So, what is your problem now?
    You can join both the tables using a simple query and get the records.
    select e1.empname, e2. empname from emp1 e1, emp2 e2 where
    e1.empname = e2.empname and e1.empid = e2.empid

  • How to insert some records in one table and some records in another table

    Interview question
    how insert records in two tables by using trigger
    CREATE or REPLACE TRIGGER Emp_Ins_Upd_Del_Trig
    BEFORE delete or insert or update on EMP
    FOR EACH ROW
    BEGIN
    if UPDATING then
    UPDATE emp2
    SET
    empno = :new.empno,
    ename = :new.ename
    --, job = :new.job
    --, mgr = :new.mgr
    --, hiredate = :new.hiredate
    , sal = :new.sal
    --, comm = :new.comm
    --, deptno = :new.deptno;
    sdate = :new.sdate,
    edate = :new.edate
    end if;
    if INSERTING then
    INSERT INTO emp2
    VALUES
    ( :new.empno
    , :new.ename
    --, :new.job
    --, :new.mgr
    --, :new.hiredate
    , :new.sal
    --, :new.comm
    --, :new.deptno
    new.sdate,
    new.edate);
    end if;
    if DELETING then
    DELETE FROM emp2
    WHERE empno = emp2.empno;
    end if;
    END;
    it is working fine but he wants to insert some specific litimit on one table and some specified limit of records in one ..
    In this senerio can i insert records by use count of records...
    please help me..

    Can you be more specific on the "Limit"
    Conditional insert can be used in this case.

  • Previous and next records in a table

    Let's say I have a table where I have
    item name sequence customer number
    I want to select these three fields where name = 'INSPECTION', but I'd also like to grab the record prior to this and the record after this, regardless of the name content. I need to do it for each customer number.
    Is it possible for a novice like me to do?
    Thank you

    What is "next record" and "previous record" for you in this context? A database table doesn't have records in any specific order. They have an arbitrary order.
    If for you, the records have the sequence as an ordering information, then you could use LAG and LEAD functions.

Maybe you are looking for