Transact SQL :: Table Lock Time Scope

May 8, 2015

I have a query which is part of bigger transaction:

;WITH CTE(
SELECT id, q,
totalQ=SUM(q) OVER (ORDER BY id ROWS UNBOUNDED PRECEDING)
FROM dbo.myTable WITH (UPDLOCK, ROWLOCK)
), CTE1 AS(
SELECT id, q_take=CASE WHEN c.Total<@qRequired THEN c.q ELSE
@qRequired-c.Total+c.q END FROM CTE
WHERE (CASE WHEN c.Total<@qRequired THEN c.q ELSE
@qRequired-c.Total+c.q END)>0
)
UPDATE t set q-=c1.q_take FROM dbo.myTable t INNER JOIN CTE1 c1 ON t.id=c1.id

Because CTE query is executed separately of update query I must put UPDLOCK hint, otherwise myTable could be changed while my query executes by some other user.(I have snapshot row committed transaction).

The problem is that my hint will hold lock on rows of myTable until the end of outer transaction(the bigger one).

But I need lock only for the time of this small query execution. What would be the best way to achieve that?

View 8 Replies


ADVERTISEMENT

Transact SQL :: Temp Table Scope On Error

Oct 12, 2015

In my sp I'm have an Insert statement. In the event that after the insert @@rowcount = 0 I'm throwing an error with RAISEERROR.

This is fine, however, in my CATCH block I'm referencing a local temp table but getting an error that it no longer exists.

My question is, does throwing an error drop any #temp tables? I thought they were in scope for the session?

View 4 Replies View Related

Problems With Transaction Scope Time Out

Oct 2, 2007

Hi, i'm trying to run wrap a transaction around a block of code to make sure every statement is carried out.  Here's what i have:
using (TransactionScope ts = new TransactionScope())
{   ...   ts.Complete();}The code executed in the ... part is a set of sql commands within my dal.  If this above expression takes less than 30 seconds everything is carried out correctly, however if it takes longer than 30 seconds i receive an sql timeout error.  I tried modify the above code to:
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(5)))
{   ...   ts.Complete();}
But it did not seem to make a difference.  I suppose the easiest option would be to increase the timeout for every sql command in my dal but i feel that the 30 second timeout is sufficient for a single command.
Appreciate if someone could tell me how this should be done correctly.  Thanks

View 2 Replies View Related

Transact SQL Probklems With Variable Scope

Jul 20, 2005

I have 24 tables named tblData1 ... tblData24 and I have a scheduledjob that runs successfully to delete all data older than 31 days.My problem is that I need to keep at least one record in each tablefor the aggregate function max() to work in one of my application'sfunctions, as if there are no records the result is null.Although I have figured out a workaround in the function using max() Iwould like to know how to change my script.Functionally I would like to get the max() value of the ID column(autoincrementing) and then add to the where "And ID <> @maxID".I have tried a few options and come unstuck with scope of variables,and tried to use a temp table to store the max values for the 24tables and got no where. Can anyone help ?Working script without the @maxID bit:-DECLARE @days VARCHAR(12)DECLARE @intData intDECLARE @SQL1 VARCHAR(2000)set @Days = 31set @intData = 1While @intData<=24BeginSET @SQL1 = 'DELETE FROM [DB1_SQL].[dbo].[tblData'+rtrim(CONVERT(char(2), @intData)) + '] Wheredatediff(Day,Datim,getdate())> '+ @daysEXEC(@SQL1)/*print @SQL1*/set @intData= @intData + 1Endgo

View 2 Replies View Related

Transact SQL :: Accumulate Alarm Time Per Event In A Log Table?

Apr 28, 2015

I have a log table in which alarm events are logged (a many relation to a main table) where EventId is the foreign key in the log table.

In this table all events related to a given incident (EventID) are logged, but it is specifically two eventtypes which is of interest, thats the "into alarm" represented by an integer value "0" in the column "EventTypeId" and the "restored represented by an integer value of "2". Each state of change has a timestamp of datetime.For each incident (EventId) there can be multiple "into alarm" and "restore" rows, there can also be other events which has no interests. Only the timediff between each "0" and "2" accumulated is of interest.

There's one more little twitch, it can occure that when the query is run, the "2" restored state is not yet present, the query should not return a result for that "0" into alarm when the "2" restored is not present, unless there was a complete alarm/restore session.

CREATE TABLE [dbo].[AlarmHistoryLog](
[EventId] [int] NOT NULL,
[EventSeq] [int] IDENTITY(1,1) NOT NULL,
[EventTypeId] [int] NOT NULL,
[EventTime] [datetime] NOT NULL,
[EventDescription] [nvarchar](250) NOT NULL,
[Comment] [nvarchar](4000) NULL,
[UserID] [int] NULL,
[ReceiverID] [int] NULL
) ON [PRIMARY]

View 5 Replies View Related

Transact SQL :: Time Series Table Which Generates A Flag For Every 10 Mins

May 15, 2015

i have a time series table which generates a flag for every 10 mins. the table looks as below. I am trying to write a sql query which gives me the start date and end date of a particular flag, each time the flag starts. i tried to do it using cursors and actually joining the table to itself based on a 10 min offset but couldn't get the required results.

startdate enddate
flag
2009-11-02 23:30 2009-11-02 23:50
-999
2009-12-08 04:50 2009-12-08 04:50 -990

View 3 Replies View Related

Transact SQL :: Create Table Named With Ending Date-time Format

Jun 25, 2015

what would be the TSQL in trying to create a new table with date-time format ending via a select into like:

select
*
into tblResults_
+
SELECT
CONVERT(VARCHAR(10),GETDATE(),112)
+
'_'
+
REPLACE(CONVERT(VARCHAR(10),GETDATE(),108),':','_')
from qryResult

View 3 Replies View Related

Transact SQL :: Select 1000 Rows At A Time From / Into A Large Temp Table?

May 12, 2015

I am using SQL SERVER 2008R2, not Denali, so I cannot use OFFSET FETCH Clause.

In my stored procedure, I am doing a SELECT INTO #tblTemp FROM... Working fine. This resultset is going to be used in an SSIS package which will generate a pipe-delimited .txt file... Working fine.

For recoverability sake, I am trying to throttle back on the commit chunks to 1000 rows per commit until there are no more rows. I am trying to avoid large rollbacks.

Q: Am I supposed to handle the transactions (begin/commit/rollback/end trans) when the records are being inserted into the temp table? Or when they are being selected form the temp table?

Q: Or can I handle this in my SSIS package for a flat file destination? I don't see option for a flat file destination like I do for an OLE DB Destination (like Rows per batch, Maximum insert commit size).

View 6 Replies View Related

Transact SQL :: Create Index On Temp Table To Reduce Run Time Of Update Query

Apr 29, 2015

I want to create index for hash table (#TEMPJOIN2) to reduce the update query run time. But I am getting "Warning!

The maximum key length is 900 bytes. The index 'R5IDX_TMP' has maximum length of 1013 bytes. For some combination of large values, the insert/update operation will fail". What is the right way to create index on temporary table.

Update query is running(without index) for 6 hours 30 minutes. My aim to reduce the run time by creating index. 

And also I am not sure, whether creating index in more columns will create issue or not.

Attached the update query and index query.

CREATE NONCLUSTERED INDEX [R5IDX_TMP] ON #TEMPJOIN2
(
[PART] ASC,
[ORG] ASC,
[SPLRNAME] ASC,
[REPITEM] ASC,
[RFQ] ASC, 

[Code] ....

View 7 Replies View Related

Variable Scope And Connection Manger Scope

Mar 13, 2008



I have taken three dtsx files and re written them into one each in its own container. I use the XML Task task alot which the File connection is set by a variable and the variable value is evaluated by expression (the expression makes up the path/filename from other variable values). All the variables that make up the connection are at the container scope. The package will not run now because it is saying that the source (created by variables) for the file connection do not exist.

It seems the answer is that file connections exist at the package level therefore the variable has to be at the package level. This seems to be alot of variables i now have to move to package level to generate the XML source connection. Which in essence makes it confusing as to which variables operate in which container.

My question is can we easily move variable scope (Not ideal as we have alot of variables at package level) Or Can we do the same for connection managers as we do for variables and have them only used in a scope? (this will be ideal as some connections only need to be at a container scope)

View 1 Replies View Related

Average Lock Wait Time

Oct 3, 2014

I keep getting an alert from a Third-Party Tool stating my server is reporting failed components with the following message

Components Reporting Problems:
Average Lock Wait Time(ms)(Critical)

When I look at sp_who2 or sp_lock I don't see anything blocking processes or anything else out of the ordinary.

View 2 Replies View Related

Lock Request Time Out Period Exceded

Mar 17, 2004

Hi,

while my db is executing a store procedure i try to view the current activity in the managent but it returns to me 'Lock request time out period exceded'. It happens until the store procedure is finished. After that everything is ok. However i can see the activity executing sp_who and the db seems to work ok, maybe a little slow.

what does it means????

Sorry for my english.
Thanks. Eduardo

View 1 Replies View Related

Lock Request Time Out Period Exceeded

Nov 8, 2006

Hi
I am getting occasional errors in the event log of our production database where we have some service broker receiving queues running.

The first error is

Lock request time out period exceeded

This is then immediately followed by

An error occurred in dialog transmission: Error: 1222, State: 51.

There are no further errors and everything seems to carry on OK after this error.

Does anybody know what the problem may be?

Anthony

View 1 Replies View Related

SQL Jobs - Cannot Obtain A LOCK Resource At This Time

May 24, 2007

Hi All,



We recently bought a new (sql) database server with 8 gb ram. I started moving the databases from our older 2005-sql to the new one. Everything goes well, except...



Some steps in our jobs do a truncate table of a delete from... When the job is running and it reaches the step where the truncation/deleting starts, it stops its execution and gives the following error :




Code Snippet

The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users. Ask the database administrator to check the lock and memory configuration for this instance, or to check for long-running transactions. [SQLSTATE HY000] (Error 1204). The step failed.




When I try to execute the procedure that does the truncation manually, it works perfect. Do you guys have an idea on what the cause of this error might be ?



Thanks a lot in advance !



(FYI: we use the enterprise edition of sql server 2005)



Grtz, Koen

View 9 Replies View Related

Lock Request Time-out Period Exceeded

Apr 1, 2008



Hi ,
i am getting error Lock request time-out period exceeded frequently
Could any one explain how can i track the Locking transactions
SP_who,SP_lock helps me partially but i need clear solution

View 3 Replies View Related

How To Lock The Store Procedure And Allow One Process To Acces It At A Time

Jul 20, 2005

Hello:I run one process that calls the following the store procedure andworks fine.create PROCEDURE sp_GetHostSequenceNumASBEGINSELECT int_parameter_dbf + 1FROM system_parameter_dbtWHERE parameter_name_dbf = 'seqNum'UPDATE system_parameter_dbtSET int_parameter_dbf = int_parameter_dbf + 1WHERE parameter_name_dbf = 'seqNum'ENDGOIf I run two processes that call the above store procedure, I mightoccasionally get the dirty data of int_parameter_dbt. I guess that iscaused by two processes accessing to the same resource simultaneously.Is there any way to lock the store procedure call from MSSQL Serverand allow only one process to access it at a time?Thanks for help.Best Jin

View 2 Replies View Related

DB Engine :: Lock Request Time Out Period Exceeded

Oct 21, 2015

We're running a SQL-Server 2012 and for a while now my accessing records from bigger tables became tricky.There is a Tomcat-8 running which sometimes can't access these tables at all or only after a long delay. As this happened first I went to the Server-Room and opened the Database with the Management Studio to see if there were any issues. open the Database but expanding the directories for "Tables" or "Views" failed after 10 Seconds with the Error 1222.

I turned the Tomcat-8 off to find out whether some unclosed connections are open. Same result, no changes even after one hour.Another 3rd-Party program which we are using seems to connect via other mechanisms to the SQL-Server (Is there a way to list current connections and their types in the Management-Studio, I'm under the impression this program does a lot of caching, it's much faster than the Management-Studio itself.The question is now how can I find out why these time-outs happen? I'm not an expert in SQL-Servers so.

View 8 Replies View Related

Trigger Scope Table

May 15, 2008

Hi,
A need a trigger to scope my data modifications but this code return EventData a NULL. Can someone help me with this?
Thanks




Code Snippet


CREATE TABLE [dbo].[_Log](

[EventID] [int] IDENTITY(1,1) NOT NULL,
[EventData] [xml] NULL,

PRIMARY KEY CLUSTERED
(
[EventID] ASC
) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

---------

CREATE TRIGGER [dbo].[TRG_Clients]
ON [dbo].[Clients]
FOR DELETE,INSERT,UPDATE
AS
INSERT INTO [dbo].[_Log](EventData)
SELECT EVENTDATA()

View 9 Replies View Related

Transact SQL :: Update Time Portion Of DateTime Field With Time Parameter

Oct 3, 2015

I hope to update a DateTime column value with a Time input parameter.  Poor attempt below but it looks like the @ApptTime param is coming in as 10:45:00.0000000 and I might have an existing @SendOnDate as: 2015-10-05 07:00:00.000...I hope to end up with 2015-10-05 10:45:00.000

ALTER PROCEDURE [dbo].[SendEditUPDATE]
@QuePoolID int=null
,@ApptTime time(7)
,@SendOnDate datetime

[code]...

View 14 Replies View Related

Transact SQL :: Converting 24hrs Time To 12 Hours Time Query Format?

Apr 21, 2015

SELECT 
    CONVERT(VARCHAR(10),attnc_chkin_dt,101) as INDATE,
    CONVERT(VARCHAR(10),attnc_chkin_dt,108) as TimePart
FROM pmt_attendance

o/p
indate   04/18/2015
time part :17:45:00

I need to convert this 17:45:00 to 12 hours date format...

View 8 Replies View Related

How To Lock A Table So Others Cannot Lock It

May 23, 2001

Hi,

I want to lock a table so others cannot lock it but able to read it inside transactions.

The coding I need is something like this: set implicit_transactions on begin transaction select * from table1 with (tablock, holdlock) update table2 set field1 = 'test' commit transaction commit transaction

I have tried the coding above, it won't prevent others from locking table1.

So, I changed the tablock to tablockx to prevent others from locking table1. But this will also prevent others from reading table1. So, how can I lock table1 so others cannot lock it but still able to read it?

Thank you for any help

View 1 Replies View Related

SQL 2012 :: Error 1222 - Lock Request Time Out Period Exceeded

Mar 21, 2013

What is this? How do I fix it? I get a ton of these and it slows down the server for 5 minutes.

An error occurred in Service Broker internal activation while trying to scan the user queue 'msdb.dbo.ExternalMailQueue' for its status. Error: 1222, State: 51. Lock request time out period exceeded. This is an informational message only. No user action is required.

View 1 Replies View Related

What Is The Scope Of A Table Variable Defined In A Dataset?

Dec 14, 2007

if a dataset doesnt use a stored proc to define a table variable, what is the scope of that table variable? Does the name need to be unique from such variables defined by other datasets?

View 4 Replies View Related

Replication Performance Degrade In Unidirectional Direction And Lock Time Out (Update Are High Than Inserts)

Feb 21, 2007

 

We recently implemented merge replication.We were expereincing. The replication is between 2 SQL Servers (2005) over same network box, and since we have introduced the replication, the performance has degraded considerably on subscriber end.

1)   One thing that should be mention is that its a "unidirectional Direction" flow of changes is from publisher towards subscriber (only one publisher and distributor as well and one subscriber ).

2) Updates are high than inserts and only one article let say "Article1" ave update up to 2000 per day and i am experiecing that dbo.MSmerge_upd_sp_Article1_GUID taking more cpu time.what should be do..

 

on subscriber database  response time is going to slow and i am experiencing a lot of number of LOCK time outs on application end.

can any one can also suggest me server level settings for aviding locking time out.

 

looking for any experieced solution/suggestion.

Thanks in advance. 

View 3 Replies View Related

Temp Table Scope In Nested Stored Procedures

Jun 8, 2001

We are migrating a SQL 6.5 application with 1900 stored procedures that use 100's of temp tables to SQL 2000.

A problem we have encountered was that we started out getting an "invalid column" errors on certain procedures. Investigation determined that the error was being generated in a nested procedure. The table that caused the error ended up being a temp table that was created using "select into". The following select statement from that temp table gave the invalid column error.

First thinking it was the "Select Into" we then discovered that the outer most procedure had created a temp table of the same name prior to executing the lower level procedure. After the select into, the next statement was a SELECT that went against what it thought was the inner temp table. However, it grabbed the outermost temp table and then couldn't find the appropriate columns and generated the error.

The solution, of course, was to rename the inner most temp table. We also remove the "select into" in the procedure by explicitly creating the temp table.

We tried creating some test procedures to attempt to reproduce this scenario without complete success.

Our test created 3 procedures (sp1 calling sp2 calling sp3) to mimic the current scenario. Sp1 created a temp table and executed sp2, which executed sp3. Sp3 created another temp table using the same name as the one created in sp1.

If we create all three procedures at the same time, it doesn't matter if we change the order in which they are created or whether we create the inner temp table explicitly or with a "select into", SQL Query Analyzer won't let us create the procedure because it finds that the temp table has been declared twice. If we create the procedures separately however, they compile and allow sp3 to create a temp table by the same name as sp1. After creating the procedures independently, they runs properly in all cases with everything in proper scope and no problems.

Admittedly, this is bad coding to start with, but what is happening with the scope of the temp tables within the stored procedures?

Thanks,
Glen Smith

View 1 Replies View Related

SQL Server 2012 :: Exec Producing Table Out Of Scope

Dec 17, 2013

I am generating some dynamic sql which I would like to run and return the data from, however when I run EXEC(@TEMP_TABLE_STRING) it cannot return the table I think because it is out of scope.

Is there a way around this.

declare@Tablename VARCHAR(150) = 'TEMP_LOCATIONS'
declare@FilterClause VARCHAR(512)=NULL
declare@Classes VARCHAR(100)=NULL
declare@IsExcel BIT = 1
DECLARE @SQL Nvarchar(MAX) = ''
SET NOCOUNT ON;

[Code] ....

View 4 Replies View Related

SQL Server 2008 :: Techniques For Ensuring Isolated Temp Table Scope?

Jul 28, 2015

what are some common techniques for ensuring an isolated temp table scope? For example, if 2 different sprocs happen to crud a temp table with the same name? I'm guessing that big SQL shops establish a standard for this early on to avoid conflicts between sprocs.

View 3 Replies View Related

Error: A Deadlock Was Detected While Trying To Lock Variable X For Read Access. A Lock Could Not Be Acquired After 16 Attempts

Feb 2, 2007

I simply made my script task (or any other task) fail

In my package error handler i have a Exec SQL task - for Stored Proc

SP statement is set in following expression (works fine in design time):

"EXEC [dbo].[us_sp_Insert_STG_FEED_EVENT_LOG] @FEED_ID= " + (DT_WSTR,10) @[User::FEED_ID] + ", @FEED_EVENT_LOG_TYPE_ID = 3, @STARTED_ON = '"+(DT_WSTR,30)@[System::StartTime] +"', @ENDED_ON = NULL, @message = 'Package failed. ErrorCode: "+(DT_WSTR,10)@[System::ErrorCode]+" ErrorMsg: "+@[System::ErrorDescription]+"', @FILES_PROCESSED = '" + @[User::t_ProcessedFiles] + "', @PKG_EXECUTION_ID = '" + @[System::ExecutionInstanceGUID] + "'"

From progress:

Error: The Script returned a failure result.
Task SCR REIL Data failed

OnError - Task SQL Insert Error Msg
Error: A deadlock was detected while trying to lock variable "System::ErrorCode, System::ErrorDescription, System::ExecutionInstanceGUID, System::StartTime, User::FEED_ID, User::t_ProcessedFiles" for read access. A lock could not be acquired after 16 attempts and timed out.
Error: The expression ""EXEC [dbo].[us_sp_Insert_STG_FEED_EVENT_LOG] @FEED_ID= " + (DT_WSTR,10) @[User::FEED_ID] + ", @FEED_EVENT_LOG_TYPE_ID = 3, @STARTED_ON = '"+(DT_WSTR,30)@[System::StartTime] +"', @ENDED_ON = NULL, @message = 'Package failed. ErrorCode: "+(DT_WSTR,10)@[System::ErrorCode]+" ErrorMsg: "+@[System::ErrorDescription]+"', @FILES_PROCESSED = '" + @[User::t_ProcessedFiles] + "', @PKG_EXECUTION_ID = '" + @[System::ExecutionInstanceGUID] + "'"" on property "SqlStatementSource" cannot be evaluated. Modify the expression to be valid.

Warning: The Execution method succeeded, but the number of errors raised (4) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.

And how did I get 4 errors? - I only set my script task result to failure

View 11 Replies View Related

Lock SQL Table Using Asp.net

Jul 23, 2004

Hi,all:
This problem almost drives me crazy, hope I can get some hints from you guyz!!!
Ok, here is the situation:
I wanna only one users 2 modify the data(update) from my page each time, and if at the same time, there are some other users connecting my database through .aspx page, they can only browse the data until the first users finish updating.
It seems I need to implement locking the database, but I am not sure how I am gonna do that using asp.net!!!
Thanx in advance!

View 5 Replies View Related

How To Lock A Table Or Row In Sql?

Nov 1, 2005

hi, i have an application that updates some records in sql tables, and i want to do a  web application that updates records in the some database-table(sql) so, my question is how can i lock the row or table  so i dont have concurrency problems.tnx in advance.

View 2 Replies View Related

Table Lock...

Nov 5, 2007

Hello Friends,
I am having a VB application running for the SQL SERVER DB. The VB application is installed on the multiple of PCs in the network. Now when I am trying to fetch the same from all the different PCs simultaneously, its amazingly fast. But the issue comes when I am trying to update the same table (but different rows) from the different PCs simultaneously. The time taken is directly proportaional to the number of users. I am not getting what could be the problem? Can any one suggest me the approch? Is it some related to table / row / page locking? As all the connections are trying to update on the same table. I checked the isolation level. Its default, "READ COMMITTED". Kindly suggest...




Thanks in advance........
Rahul Jha

View 14 Replies View Related

Table Lock

Jun 5, 2008

Hi Gurus,

How can we know that particular table is locked.



Thanks,
ServerTeam

View 1 Replies View Related

How To Lock A Table

Mar 21, 2006

Hai to all,

I want to lock a patricular table during my transaction is this possible, for Example

Create sp() as
BEGIN
Lock Table
Do Some work
Relaese the Lock
END

like this.

View 3 Replies View Related







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