SQL Server 2012 :: Find Queries That Lock Tables Or Not Using Primary Key While Running Update

Jul 20, 2015

I need to search for such SPs in my database in which the queries for update a table contains where clause which uses non primary key while updating rows in table.

If employee table have empId as primary key and an Update query is using empName in where clause to update employee record then such SP should be listed. so there would be hundreds of tables with their primary key and thousands of SPs in a database. How can I find them where the "where" clause is using some other column than its primary key.

If there is any other hint or query to identify such queries that lock tables, I only found the above few queries that are not using primary key in where clause.

View 2 Replies


ADVERTISEMENT

SQL Server 2012 :: Perform Update But Skip Lock

Mar 7, 2014

I open query analyser and on one tab I update a record in a transaction and hold it.

begin tran
update customers set territory = 'x' where customer = 'A00001'
--rollback tran

In a second tab I attempt to update all records in the table

update customers set carrier = ''

Clear this fails because of the lock placed during the first script and this is fine.

However, is there a way to get the 2nd script to ignore the locked rows and just update as many as it can? The obvious answer seemed to be the READPAST hint like follows…

update customers with (READPAST) set carrier = ''

…but this is still blocked by the original lock. I’ve tried combining it with all sorts of other table hints but all seem to get blocked.

The following does work, ignoring the lock and not returning the data

Select * from customers with (READPAST) where customer = 'A00001'

I’ve tried combining this with the update like so…

update customers
set carrier = ''
from customers with (READPAST)
where customer = 'A00001'

..but this is blocked too.

I’m so desperate I tried moving the update into a cursor and update one row at a time. Nothing worked. I thought I might be able to do something like this

If (Select count(*)
from customers with (READPAST)
where customer = 'A00001') > 0
--then perform update

..but this returns a value of 1 even though the following returns no rows.

Select * from customers with (READPAST) where customer = 'A00001'

View 9 Replies View Related

How To Lock Tables While Job Is Running

May 12, 2008



Hi Everyone,

I have got a Sql Job which takes quite a while to finish and use sql tables quite extensively.

I want to prevent all other users to access the tables used by Job while job is runing. But they will be able to use table as normal after job finishes.

any ideas ?? I guess I might need to play around Roles and permission but not sure.

any help much appriciated.

Regards,
Furrukh Baig

View 5 Replies View Related

Update Statement Performing Table Lock Even Though Where Condition On Clustered Primary Index?

Jul 20, 2005

Hi All,I have a database that is serving a web site with reasonably hightraffiic.We're getting errors at certain points where processes are beinglocked. In particular, one of our people has suggested that an updatestatement contained within a stored procedure that uses a wherecondition that only touches on a column that has a clustered primaryindex on it will still cause a table lock.So, for example:UPDATE ORDERS SETprod = @product,val = @valWHERE ordid = @ordidIn this case ordid has a clustered primary index on it.Can anyone tell me if this would be the case, and if there's a way ofensuring that we are only doing a row lock on the record specified inthe where condition?Many, many thanks in advance!Much warmth,Murray

View 1 Replies View Related

SQL Server 2012 :: Trigger For Update Action Without Primary Key

Jun 18, 2015

I am writing a trigger for getting values to auditlog table when the values gets updated. Below is the code of my trigger.

CREATE TRIGGER [dbo].[Update_Temp] ON [dbo].[Temptable1] FOR UPDATE
AS
DECLARE @bit INT ,
@field INT ,
@maxfield INT ,
@char INT ,
@fieldname VARCHAR(128) ,
@TableName VARCHAR(128) ,

[Code] ....

The code is working fine when the table has primary key associated. However due to some restrictions I will not be able to have a primary key for some tables. I want to implement the same trigger in those tables too. When there is primary key, that primary key needs to get inserted into the audit table and if there is no primary key, i want a specific column value to get inserted instead of the primary key value into the audit table.

For example, i have a student table in which there is a student id, name, dob. there is no primary key defined for the table. So when i update the name or dob, i need the student id to get inserted into the Pk column of the audit table.

I tried modifying the code by checking the @pkcols for Null and if its null to get the old value as the primary key however I was not able to do it .

View 1 Replies View Related

SQL 2012 :: SSMS Object Explorer Lock Timeout When Running Compression Script

Jan 21, 2015

ALTER TABLE [dbo].[TableNameExample] REBUILD PARTITION = ALL
WITH (DATA_COMPRESSION = PAGE)

The table is 110 GB, so will take time to compress. But it is one table in a database with 60 tables. Why would executing this statement, cause lock timeout on Object Explorer in SQL Server Management Studio? Users cannot drill down objects in this database without getting lock timeout.

When I cancel the compression script, users of SSMS can access objects in this database again from the GUI. Why does compressing a specific table affect access to all tables metadata? I cannot find anything on the internet but I am sure this has happened to other people.

View 3 Replies View Related

Transact SQL :: Script To Find List Of Queries Currently Running In Database With User Login And Host Name?

Dec 30, 2014

How to find the list of queries currently running in the Database with User Login Information.

Since my database application is running slow, to find the slow queries.

View 8 Replies View Related

SQL Server 2012 :: Running Sum With Reset Option And BULK Update

Jul 22, 2015

I have come up with an issue where I want to update data in a table using bulk/SET update to get the result shown in below code with output in column titled "Arrear Amt".

Please use this test data.

CREATE TABLE ##vOD_Calc
(
Seq_No INT ,
Contract_id INT ,
Rental_id INT ,
Actual_OD INT ,
Logic_OD INT ,
Due_dte DATETIME ,

[Code] .....

Logic required is that once the sum of column [ArrearAmt] of current row and all previous rows becomes greater than $100 then column [ChArrrearAmt] should show that summed up value and in else case the column [ChArrrearAmt] should show the same value as that of column [ArrearAmt].

Once the column [ChArrrearAmt] reaches the threshold of $100 then the same cycle should start again i.e. in above example rental#1 had $37.17 < $100 then rental#1 + rental#2 is also < $100 and at rental#3 sum of rental#1, rental#2 and rental#3 becomes $111.51 which is greater than $100 so its updated in column [CHArrrearAmt]. The same cycle start overs from rental#4 onwards however the summation of [ArrearAmt] will now begin after rental#4 onwards and not from the starting.

Below is the loop based SQL script which handles the above situation, however in BULK its a total deterioration of performance if thousands of rows are to be processed i.e. with a contract having multiple rentals.

The case here is that I have to use the result of previously updated column value of [ChArrrearAmt] to take decision for the next row, however with BULK update since the row is not yet updated with latest amount therefore the decision on next row is also giving wrong result.

This is the code with which I have achieved to update the column 'chArrear Amount', however its a loop based solution and performance killer.

INSERT INTO ##vOD_Calc_loop
( Rows_count ,
contract_id
)
SELECT COUNT(*) ,
T.Contract_id
FROM ##vOD_Calc T
GROUP BY T.Contract_id

[Code] ....

View 4 Replies View Related

Update Query With Sub-queries To Find The Values

Jul 20, 2005

Help, please. I am trying to update atable with this structre:CREATE TABLE Queue (PropID int, EffDate smalldatetime,TxnAmt int)INSERT Queue (PropID) SELECT 1INSERT Queue (PropID) SELECT 2INSERT Queue (PropID) SELECT 3....from this table...CREATE TABLE Txns (PropID int, TxnDate smalldatetime,TxnType char(1), TxnAmt int)INSERT Txns SELECT 1 '20000201', 'B', 100000INSERT Txns SELECT 1 '20020515', 'B', 110000INSERT Txns SELECT 1 '20020515', 'A', 120000INSERT Txns SELECT 1 '20020615', 'c', 130000....only certain txn types are okay, and they have an orderof preference...CREATE TABLE GoodTxnTypes (GoodTxnType char(1), Pref)INSERT GoodTxnTypes SELECT 'A', 1INSERT GoodTxnTypes SELECT 'B', 2The idea is to fill in the NULL fields in the Queue table,according to a rule -- the transaction must be the latesttransaction within a date window, it must be one of the goodtxn types, and if there are two txns on that date, choosethe txn by the preferred txn type (A is preferred over B,according to the field Pref).If the time window were 20020101 to 20030101, the txnselected to update the Queue table would be this one:INSERT Txns SELECT 1 '20020515', 'A', 120000 -- there aretwo in the time window that are type A or B; they areboth on the same day, so the 'A' is preferred.If the time window were 20000101 to 20010101, this wouldbe selected because it is the only A or B type txn inthe interval:INSERT Txns SELECT 1 '20000201', 'B', 100000I'm looking for a statement that starts...UPDATE Queue SET EffDate = ...., TxnAmt = .... (EffDate,in this table, is the same as TxnDate in the Txn table).Assume we have @FirstDate and @LastDate available.Help, please. I'm getting stuck with (a) a sub-query tofind the relevant Txn records, and (b) another sub-querywithin that to find the MAX(TxnDate) within the timewindow. Filtering the Txn records on the basis of theGoodTxnTypes table is easy, as is ordering what is returned.But I'm having trouble joining the sub-queries back to theQueue table on the basis of PropId.

View 1 Replies View Related

SQL Server 2012 :: Find All Tables Used In Any Stored Procedure

Feb 14, 2015

I have a table with the list of all TableNames in the database. I would like to query that table and find any tables used in any stored procedure in that DB.

Select * from dbo.MyTableList
where Table_Name in
(
Select Name
From sys.procedures
Where OBJECT_DEFINITION(object_id) LIKE '%MY_TABLE_NAME%'
Order by name
)

View 7 Replies View Related

SQL Server 2012 :: Find Names Of Tables For A Particular User

Feb 18, 2015

how to find the names of the tables owned by the particular user in sql server and how to display the distinct object types owned by the particular user.

View 1 Replies View Related

Script: Find Tables Without Primary Keys

Aug 3, 2002

...got tired of looking at them by hand.

Cheers
-b

DECLARE @vcDB varchar(20),@vcSchema varchar(20),@vcTable varchar(200)

Select @vcDB='mydb',@vcSchema='dbo'

DECLARE cLoop cursor for
select TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where TABLE_CATALOG=@vcDB
and TABLE_SCHEMA=@vcSchema
order by TABLE_NAME ASC

open cLoop

FETCH NEXT FROM cLoop INTO @vcTable
WHILE @@FETCH_STATUS=0
BEGIN
if not exists (SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = @vcSchema
AND TABLE_NAME = @vcTable
AND CONSTRAINT_TYPE = 'PRIMARY KEY')
print @vcTable + ' does not have a primary key'

FETCH NEXT FROM cLoop INTO @vcTable
END
Close cLoop
DEALLOCATE cLoop

View 2 Replies View Related

How To Find All Tables That Have An Identity Column As A Primary Key

Mar 6, 2008

How do i find all the tables that have an Identity Column as a primary key in a database. Thanks.

View 8 Replies View Related

SQL Server 2012 :: Find Common Link Between Two Tables In Database Without Key Constraints?

Jul 17, 2015

CREATE TABLE [Table 1] (
Id varchar,
TableTwoId varchar,
OtherData varchar )
CREATE TABLE [Table 2] (
Id varchar,
MoreData varchar )

What is the link between these two tables?

I have databases that have zero keys defined, no foreign key constraints, no unique value constraints. I cannot assume that an Identity column is the Id. The end game is be able to output that [Table 1].[TableTwoId] = [Table 2].[Id] but cannot assume that all linkage in the database will be as simple as saying "if the field name contains a table name + Id then it is the Id in that table."

Currently have written a script that will cycle through all columns and start identifying keys in singular tables based on the distinctness of the values in each column (i.e. Column1 is 99% distinct so is the unique value). It will also combine columns if the linkage is the combination of one or more columns from Table 1 = the same number of columns in Table 2. This takes a long time, and it somewhat unreliable as IDENTITY columns may seem to relate to one another when they don't.

View 2 Replies View Related

How To Find All Primary And Foreign Key Columns In All Database Tables

Apr 17, 2014

how to find all primary key columns & foreign key columns in all database tables?

View 1 Replies View Related

How To Find Missing Records From Tables Involving Composite Primary Keys

Nov 23, 2006

Table 1







     Code
    Quarter

500002
26

500002
27

500002
28

500002
28.5

500002
29

 

Table 2







     Code
           Qtr

500002
26

500002
27

 

I have these two identical tables with the columns CODE & Qtr being COMPOSITE PRIMARY KEYS

Can anybody help me with how to compare the two tables to find the records not present in Table 2

That is i need this result







    Code
   Quarter

500002
28

500002
28.5

500002
29

I have come up with this solution

select scrip_cd,Qtr,scrip_cd+Qtr from Table1 where
scrip_cd+Qtr not in (select scrip_cd+qtr as 'con' from Table2)

i need to know if there is some other way of doing the same

Thanks in Advance

Jacx

View 3 Replies View Related

SQL Server 2012 :: How To Perform Update Query That Involves Multiple Tables

Aug 31, 2015

I am trying to run an update statement against a vendor's database that houses HR information. If I run a regular select statement against the database with the following query, it returns without error:

SELECT "QUDDAT_DATA"."QUDDAT-INT", "NAME"."INTERNET-ADDRESS", "QUDDAT_DATA"."QUDFLD-FIELD-ID", "QUDDAT_DATA"."QUDTBL-TABLE-ID"
FROM "SKYWARD"."PUB"."NAME" "NAME", "SKYWARD"."PUB"."QUDDAT-DATA" "QUDDAT_DATA"
WHERE ("NAME"."NAME-ID"="QUDDAT_DATA"."QUDDAT-SRC-ID") AND "QUDDAT_DATA"."QUDTBL-TABLE-ID"=0 AND "QUDDAT_DATA"."QUDFLD-FIELD-ID"=16 AND "QUDDAT_DATA"."QUDDAT-INT"=11237When I try to convert it into an

[Code] ....

I am assuming I am receiving this error because it doesn't know where to find QUDDAT-INT? How can I fix that?

The "QUDDAT-INT" column houses the employee number. So in the case of the SELECT query above, I am testing against a specific employee number.

View 9 Replies View Related

SQL 2012 :: Queries Based On ER Diagram And Joining Tables

Feb 22, 2015

I need to create a few select queries based on an er diagram.

These are my Create Table statements and import statements:

Create Table Agent (Aid integer primary key, Pid integer, aName text);
Create Table Product (Pid integer primary key, pName text);
Create Table Supplier (Sid integer primary key, sName text);
Create table Supplies (Sid integer, Pid integer, price decimal(8,2));

.import agent.txt Agent
.import product.txt Product
.import supplier.txt Supplier
.import supplies.txt Supplies

I think I got all my create table statements are correct.

I need to Find the number of agents for each supplier that has at least one agent. The result should be tuples of the form (sid, sName, number of agents)

-Select Sid, sName, count(Aid) from Agent A join Supplier S on (S.Sid = A.Sid) group by S.Sid, S.sName, Aid;
But it gives me this error: no such column: A.Sid

Im thinking I might have a problem with my create table statement and/or primary key statements?

View 9 Replies View Related

SQL Server 2008 :: How To Find Order Of Lock Taken And Released

Feb 16, 2015

I have express edition [advance] of sqlserver 2008 r2 , is it possible to trace every event with out using profiler as u know it does not ship with it.

Basically i want to see how locks are taken and released in each isolation level when query is executed. I am using

SELECT resource_database_id, t.resource_type , t.resource_associated_entity_id,partitions.index_id,blocking_session_id,
indexes.name as index_name,o.name,
t.request_status, t.request_mode,t.request_session_id,
t.resource_description

[code]....

But i am not sure of the order becuase total_elapsed_time is same for many locks

like

resource_typeresource_associated_entity_idrequest_session_idrequest_modeindex_namenameresource_description
DATABASE051SNULLNULL
OBJECT209427886651Sch-SNULLwt
OBJECT209427886652IXNULLwt
PAGE7205759715088793652IXPK_wtNULL1:204815
KEY7205759715088793652XPK_wtNULL(4fb98fd9bfad)
DATABASE052SNULLNULL

View 5 Replies View Related

SQL 2012 :: Sleeping Queries Blocking Rebuild Index And Update Statistics Job In AlwaysOn

Feb 3, 2015

At one of your client sides we have configured Always on with synchronous mode.Also we have schedule rebuild index and update statistics job which runs in night every alternate day. the issue is there are more then 100 sleeping queries which is blocking update statistics job.

I have to stop update statistics job manually once i come to office manually.

Once I have killed blocking sleeping query but then other sleeping query blocked it and so on.

View 4 Replies View Related

SQL 2012 :: Insert Data Onto Tables Having Primary And Foreign Key Relations?

Oct 31, 2015

Is there anyway to get the order in which data to be import on to tables when they have primary and Foreign Key relations?

For ex:We have around 170 tables and when tries to insert data it will throw error stating table25 data should be inserted first when we insert data in table 25 it say 70 like that.

View 3 Replies View Related

SQL 2012 :: Possible To Find All Tables That Has A Join With Given Table In Database

Jan 7, 2015

I need to find all tables which has a join (either inside an sp, view, etc) with my given table in a db.

sys.dm_sql_referencing_entities doesn't work here.

Note: i dont want to identify by FK References, for 2 reasons:

1) tables might not met with a join (just FK was defined)
2) sometimes, a join happened between tables, without an FK defined

View 1 Replies View Related

Urgent: How To Find Total No. Of Queries In SQL Server 7

Sep 12, 2000

Is there a way to find out total number of queries ran i.e by day/hour or since the database was brought up in SQL Server 7?


Thanks in advance,

View 1 Replies View Related

SQL Server 2008 :: Find Out Top Expensive Queries

Apr 22, 2015

How do I find out top expensive queries from SQL Server 2008 – Standard edition ?

View 9 Replies View Related

Does SQL Server Put A Shared Lock On All Tables Within A Transaction?

Feb 17, 2006

Would table1, table2 and table3 in code below, be locked with a shared lock from start of transaction to the end of transaction Or they would only be locked for the duration of  their update, or insert statements and not for the entire transaction? Default isolation level is in effect in SQL Server.
 begin tran   update table1 set column1 = 100   if @ERROR = 0     begin       declare @stat int       set @stat = (select stat from table2 where  employeeid = 10)      insert into table3 (col1, col2) values (@stat , 325)      if @@ERROR = 0          commit tran      else         rollback tran     end   else      roll back tran

View 2 Replies View Related

SQL Server 2014 :: Does Running Multiple Queries In Same SP Cause Latency

May 14, 2014

I have the following:

(a) One Dynamic SQL Query that takes 37 ms when run as a single query or in an SP.

(b) Three SQL Indexed View queries that take 0 ms when run together.

When i add (a) + (b) in the same SP, i should get 37 ms + 0 ms = 37ms, but NO it takes 400 ms.

What is causing the extra 363 ms of latency.

View 9 Replies View Related

SQL Server 2008 :: Queries Running Against To A Table In Database

Jun 15, 2015

How can we get most frequent queries that are running against to a table in our database?

View 3 Replies View Related

Lock Table For Queries With Query WAITFOR

Sep 13, 2007

Hi all.

How can I lock table with longtime query?

View 8 Replies View Related

How To Find A Running Application In SQL Server?

May 15, 2007

How to find a running application in SQL Server?
Hi
In SQL Server (7.0, 2000), we know HOST_NAME() in a DEFAULT definition is used to record the workstation name of computers. But I need to find the name of the application which interacts my DB from the workstations. Is it possible? Please help me
Regards
Ahmed Sahib
ibnukuraish@gmail.com

View 3 Replies View Related

Analyzing Lock Order Of Queries Against Same Table To Prevent Deadlocks

Aug 5, 2014

I need to discover the actual order in which locks are acquired on a table during a query.

This with a goal of analyzing the lock order of queries against the same table to prevent deadlocks.

I'm using SQL Server 2008 R2.

From Management Studio I execute:

begin transaction
<my query>
exec sp_lock
rollback transaction

In the output I see interesting information about which locks are acquired, but:

- are this locks ordered by the time they're acquired? That is, can I be sure that lock at row n is acquired before lock at row n+1?
- if not, how can I get this information?

View 4 Replies View Related

SQL Server 2008 :: How To Find Which Queries / Processes Causing Large Memory Paging Rate

Mar 30, 2015

Our monitoring tool shows that our production system periodically experiencing large rate - up to 800 memory pages/sec. How to find out which particular queries, S.P., processes that initiate this?

View 3 Replies View Related

SQL 2012 :: Single Query To Update Same Column Name In Different Tables With Where Condition?

Sep 25, 2014

I have two tables table1 and table2 and having a common column "col1"

When i ran the following query

UPDATE table1, table2 SET col1=FALSE WHERE id = 1;

getting the following error

Error Code: 1052 Column 'col1' in field list is ambiguous

id column exist in both the tables and need to update both the tables to false where the id is equivalent to 1.

how to achieve this in single query?

View 4 Replies View Related

SQL Server 2008 :: How To Find All Agent Jobs That Are Currently Running By Query

May 29, 2013

When I give job Id in filter of this query this will give job status of "Success" but actually my job is currently in executing stage. I want to get all jobs that are currently in executing status.

Use msdb
go
select distinct j.Name as "Job Name", --j.job_id,
case j.enabled
when 1 then 'Enable'
when 0 then 'Disable'

[Code] ....

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved