SQL query to get the deadlocks in SQL SERVER 2008 [duplicate]

You can use a deadlock graph and gather the information you require from the log file. The only other way I could suggest is digging through the information by using EXEC SP_LOCK (Soon to be deprecated), EXEC SP_WHO2 or the sys.dm_tran_locks table. SELECT L.request_session_id AS SPID, DB_NAME(L.resource_database_id) AS DatabaseName, O.Name AS LockedObjectName, P.object_id AS LockedObjectId, … Read more

Set column as primary key if the table doesn’t have a primary key

This checks if primary key exists, if not it is created IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND TABLE_NAME = ‘Persons’ AND TABLE_SCHEMA =’dbo’) BEGIN ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id) END ELSE BEGIN — Key exists END fiddle: http://sqlfiddle.com/#!6/e165d/2

How to improve a case statement that uses two columns

You could do it this way: — Notice how STATE got moved inside the condition: CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN ‘”AUTHORISED”‘ WHEN STATE = 1 AND RetailerProcessType = 2 THEN ‘”PENDING”‘ ELSE ‘”DECLINED”‘ END The reason you can do an AND here is that you are not checking the … Read more

Avg of a Sum in one query

I think your question needs a bit of explanation. If you want to take the sums grouped by t.client you can use: SELECT t.client, SUM(t.asset) FROM the-table t GROUP BY t.client Then, if you want to take the average of this sume, just make: SELECT AVG(asset_sums) FROM ( SELECT t.client, SUM(t.asset) AS asset_sums FROM the-table … Read more