NOLOCK/ROWLOCK (good Or Bad Guys?)
Nov 9, 2007
Reading about avoiding deadlocks in SQL, I have found different opnions about whether using or not NOLOCK/ROWLOCK hints on SELECT/UPDATE/DELETE statements. I have several applications executing transactions on the same databases and tables, including inserts, updates and deletes. I wonder if by using NOLOCK/ROWLOCK I could decrease the chances of having deadlocks. At least using ROWLOCK on my update statements?. I just need some advice here.
Regards.
View 2 Replies
ADVERTISEMENT
May 22, 2008
Hello all.
I'm a litle confused about what's best to use, either isolation levels or locking per table.
Cause there are some queries in the stored procedures where I don't need locking i.e. when I check the status of client, but other queries where I do need locking like when I check the existence of a product.
What's best to use, can I combine both? Could you explain it thecnically?
lots of thanks in advance
View 1 Replies
View Related
Feb 10, 2015
I have a stored procedure that updates a table. I also have an UDF that allows dirty reads (nolock).
What's the precedence level in SQL server? If I add xlock,rowlock to the update statement, will the dirty read wait for the update transaction to commit, or will it perform a dirty read regardless of the locking scheme in the update statement?
View 0 Replies
View Related
Mar 12, 2007
Here is the situation i am stuck with, see the example first and below explained the problem:
-- 'SESSION A
create table foo (
id integer,
pid integer,
data varchar(10)
);
begin transaction
insert into foo values ( 1, 1, 'foo' )
insert into foo values ( 2, 1, 'bar' )
insert into foo values ( 3, 1, 'bozo' )
insert into foo values ( 4, 2, 'snafu' )
insert into foo values ( 5, 2, 'rimrom' )
insert into foo values ( 6, 2, 'blark' )
insert into foo values ( 7, 3, 'smeg' )
commit transaction
create index foo_id_idx on foo ( id )
create index foo_pid_idx on foo ( pid )
begin transaction
insert into foo values ( 9, 3, 'blamo' )
-- 'SESSION B
begin transaction
select id, data from foo with ( updlock, rowlock ) where id = 5;
-- Problem:
-- Uncommitted transaction in session A, with insert into table FOO, aquires lock on index foo_pid_idx which BLOCKS select with ( updlock, rowlock ) in session B.
-- Insert should aquire only exclusive rowlock. Why does insert block select with ( updlock, rowlock )?
Appreciate your help,
Rajesh.
View 5 Replies
View Related
Jul 18, 2001
Hello,
Is there any way to specify the sql server to use row level locking in transaction.
Thanks
Val
View 1 Replies
View Related
Jan 28, 2008
Advantage and disadvantage of using rowlock in sql server 2005.
View 4 Replies
View Related
Oct 26, 2007
Him
I am trying to issue the following statement to lock a record with inner join but I have an error:-
SELECT amaster.acctno,bmaster.balance,bmaster.YEAR
FROM amaster [ROWLOCK] with (Xlock)
INNER JOIN bmaster
ON amaster.acctno = bmaster.acctno
WHERE (bmaster.YEAR = 2007) acctno = 10000100
ORDER BY amaster.acctno
The error:
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "amaster.acctno" could not be bound.
Thanks
View 9 Replies
View Related
Jul 20, 2005
Hello,I need to lock only one row with exclusive lock (nobody else can see ormodify this row), but when I use "with (xlock, rowlock)" it doesn't work.XLOCK always locks whole table.Can anybody help me?Thanks in advance.Magda
View 1 Replies
View Related
Feb 8, 2008
Hi,Sql-Server 2000, 2005.A report fetches a lot of rows using the "WITH (ROWLOCK)" syntax (thesql is generated on the fly by a tool and not easily changeable).SELECT col1, col2 FROM mytab WITH (ROWLOCK) WHERE ...."The select-clause runs for several minutes.Another user fetches one of those rows and tries to update it. Theresult is a lock timeout.I suppose that the long running select-clause has put a shared lock onthe rows and the updater (exclusive-lock) will have to wait for thelong-running select and so the lock timeout is expiring.Are all those rows "shared locked" until all are fetched?Would there be any change if the "WITH (ROWLOCK)" is removed, isn'talthough "shared lock" the default behaviour?The "WITH (NOLOCK)" would probably help?What about the definition of optimistic concurrency, shouldn't allselect-clauses contain "WITH (NOLOCK)" to allow an optimisticconcurrency scenario?Regards Roger.PS. Probably some misunderstanding from me here, but this should bethe right place to get it right.
View 8 Replies
View Related
Dec 3, 2007
I've got a SELECT WITH (UPDLOCK, ROWLOCK) WHERE followed by an UPDATE WHERE statement. The results of the SELECT statement are deserialized in C# and updates are made to the deserialized object. Then the object is serialized back into the table with the UPDATE statement. I've got this code running within a transaction scope with the ReadCommited isolation level.
My service receives requests to update data and the requests can come in on different threads. What I'm seeing, is that once in a while, the log messages from my application indicate that two different threads are able to issue the above SELECT statement and both are receiving results. This is a problem since the thread that issues the last UPDATE will overwrite the changes made by the first. Each thread has its own connection and transaction scope.
I've researched all over the place and have tried a few different things, but all things point to the fact that query hints are just hints and that SQL may or may not pay attention to them. If that's the case, how am I suppose to perform a SELECT with the intention of updating so that no one else can do the same? I haven't tried table level locking, but I'd really like to avoid that if possible.
-Mike
View 4 Replies
View Related
Apr 19, 1999
Hi all!
Steve suggested I post my question here because this is where all the "experts" reside who like a little challenge. I'll simplify my problem down to two example tables with two fields each for the purpose of solving this "hard part". My only requirement for the solution is that it has to be a SQL only solution (no stored procs) as my client can only run Access - yuck...
Here's the deal. There are two tables, PEOPLE and JOBS. They look like this:
PEOPLE Table:
ID NAME
------ ------
1 Adam
2 Bill
3 Carl
4 Dave
JOBS Table:
DESC ASSIGNED_TO
----- -----------
Clean 1
Wash 2,3
Dry 2
Polish 1,3,4
I want to report which people are assigned to which jobs as shown. One line per job with the names concatenated with commas in between:
Clean Adam
Wash Bill,Carl
Dry Bill
Polish Adam,Carl,Dave
All four fields are TEXT fields in this design, but they don't have to be. I have full control over the database, fields, types, etc. If there's a better way then just suggest it. As you can see, the "ASSIGNED_TO" field is a concatenation of the IDs. Goal is just to report the DESC and people's NAMEs.
How about it? Any slick way of doing this? Played around with using SubQueries, IIF, LIKE on ID and ASSIGNED_TO, and came close but never got it all.
I appreciate any tips or suggestions. Thanks a bunch!
John
View 2 Replies
View Related
May 15, 2008
I have a table with values
id diff
1 5
2 10
5 5
6 15
7 20
8 10
10 5
11 10
12 15
I need a sum of such records whose id are continous.I mean the output should be
id sum
2 15
8 50
12 25
Id 1 & 2 are continous so it is added.But after 2 the next number is not 3 so it wont be in the sum of 1 & 2.From 5 to 8 numbers are continous so those diff are added & so on.
View 12 Replies
View Related
Jan 10, 2007
My question is can anybody explain Cascade Update and Deletes and plz tell me like i am your student. Thanks in Advance
Danny D
View 3 Replies
View Related
Nov 3, 2007
I have these queries
SELECT sum(cantidad) AS suma FROM Movimiento WHERE ID=[puntp] AND id_sorteo=[sorteo] AND tipo="Entrada";
SELECT sum(cantidad) AS resta FROM Movimiento WHERE ID=[puntp] AND id_sorteo=[sorteo] AND tipo="Salida";
I want to join in one simple query and i want to display the result of suma-resta
Thnk you ! i hope u can help me, I'm going to explode my brain hehe
View 4 Replies
View Related
Jan 5, 2004
can someone post me an example trigger where.. inserting a new record in one table, creates a new record in another table with a new unique identifier incrementing by 1 from the last record.
so that I can edit it to suit my own work like:
eg. when I insert new person into people table, using a person_no as key.
= creates new pay record in pay table ith a pay_id as key like '0004' 1 more than the last record if it was '0003', and then adds that new person_no to the record for reference.
I know this is a really easy trigger, but it would be my first! Any example to edit would be great! thanks in advance
View 4 Replies
View Related
Oct 25, 2007
Ok i've tried everything setting table collation to cyrillic setting the whole table language settings to Russian nothing works-i can only save ?????? instead of Russian symvols.(yes datatype is ntext not just text) I can directly input Russian letters from EMS SQL manager, and it will be ok, and i can even read it on my pages. But even if i try to execute SQL command through EMS manager (as opposite to just typing in the data) it will give me ????? again. If I save my ASP.net page in unicode it will give me ?? with some weird ` types symbols-but 70% of symbols would still be ????. I have already spend 45 hours googling and browsing forums but i still cannot solve it! I am so frustrated!
MS SQL Server 2005 Framework 2 ASP.net code looks like Win XP sp2
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.Odbc;
using System.Data.SqlClient;
public partial class registration : System.Web.UI.Page
{
private const string ConnStr = "server=(local);database=main;Trusted_Connection=yes";
private const string ConnStr = "server=(local);database=main;Trusted_Connection=yes";
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=(local);database=main;Trusted_Connection=yes;");
///ыуаыпвараеоеаореавп is russian random letters
SqlCommand myCommand = new SqlCommand("UPDATE quest SET Name='ыуаыпвараеоеаореавп' WHERE id=1", myConnection);
myConnection.Open();
SqlDataReader dr = myCommand.ExecuteReader();
myConnection.Close();
if i manually stop the script here and look at my dr variable i will see exactly sql command that i wrote (with no ????) but after execution in my database it is still ??????????????????????????????
Best Regards
View 6 Replies
View Related
May 8, 2007
i use a teltonika t-modem gsm modem..
it's quite new actually and it is connected to my PC thru a usb port..
my problem now is that
i can,t seem to get the hang in storing received messages in
my SQL database..
the code goes like this..
a receive button is clicked to generate an instance
where all SMS sent to my sim card would then be accessed by my gsm modem..
private void btnReceive_Click(object sender, EventArgs e)
{
ListViewItem Component;
Cursor c = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
listView1.Items.Clear();
btnReceive.Enabled = false;
objGsmIn.Device = cmbDevice.SelectedItem.ToString();
objGsmIn.LogFile = txtLogging.Text;
if (cmbDeviceSpeed.SelectedIndex == 0)
{
objGsmIn.DeviceSpeed = 0;
}
else
{
objGsmIn.DeviceSpeed = System.Int32.Parse(cmbDeviceSpeed.Text);
}
objGsmIn.Storage = fMsgStore.MsgStorage;
if (fMsgStore.DelMsg == true)
{//deletes your message after receiving
objGsmIn.DeleteAfterReceive = 1;
}
objGsmIn.Receive(); //this checks your new incoming messages
if (objGsmIn.LastError == 0)
{
objGsmIn.GetFirstMessage();
while (objGsmIn.LastError == 0)
{
//continously receive all messages..
Component = listView1.Items.Add(objGsmIn.MessageSender);
Component.SubItems.Add(objGsmIn.MessageData);
objGsmIn.GetNextMessage();
}
txtResults.Text = "Messages Successfully Received..";
}
else
{
//error in message receiving process..
txtResults.Text = "Error " + objGsmIn.LastError + "(" + objGsmIn.GetErrorDescription(objGsmIn.LastError) + ")";
}
btnReceive.Enabled = true;
Cursor.Current = c;
}
now my problem is that i cant figure out where i would place my stored procedure
in storing those messages to my database..
the problem is that..
if i place my stored procedure on the 1st "IF" statement..
it will only save my 1st incoming message..
but another thing is that if i put it under my "WHILE" statement..
dont you think that it will continiously loop?
meaning to say that the next tym i tried to access all my received messages
it would definitely store all the previously read messages again to my database..
which then creates multiple copies of my previously stored messages again and again
well i hope you get the gist of what i mean..
its quite complicated to explain..
but then again thanks a lot for taking notice on my post regarding this..
thanks!!^_^
another thing..i used the active xperts c# application in order to
create this application..
View 2 Replies
View Related
Mar 29, 2007
hello ppl.......
've installed sql 2005 xpress with advanced services......also installed the toolkit that came along..
all 'm interested in is to perform certain data mining operations on the adventureworks db..
;ve also installed the advn works db.........
now here is the prob.......
jus like how the sql online book instructed me i first started off with the datamining tutorial..where i was told to first OPEN BIDS select new PROJECT then make sure that the analysis Services template was selected and then go ahead with selection of the particular sln file....
the problem is that I DON'T SEE ANY ANALYSIS SERVICE TEMPLATE....all i c is a REPORT template..
i really need help guys..... 'm new to .net really feeling helpless...
please hurry guys....
thx a ton..
hanish
View 5 Replies
View Related
Jun 7, 2007
I have a SSIS package that is run from one job, nowhere else. The package has TransactionOption NotSupported.
In the SSIS package I first have a sequence container that has TransactionOption Required (Serializable). The sequence container contains several Execute SQL tasks that access the same SQL Server 2005 database. The Execute SQL tasks have TransactionOption supported / Serializable. The first SQL statement is:
select p.column_name
from table_name p with (XLOCK, ROWLOCK)
where p.second_column_name = 'COLUMN_VALUE'
After this there are a couple of SQL tasks, and finally a task containing the following SQL:
select p.third_column_name
from table_name p
where p.second_colomn_name = 'COLUNM_NAME'
The idea is that the first query exclusively locks the row in the table_name-table for mutual exclusion purposes, i.e. so that if for some reason the SSIS package would be executed simultaneously two or more times, only one package execution could lock the row and proceed and the other executions will have to wait. There's an index on column second_column_name in the table to avoid the select locking other rows in addition to the required row.
Some questions:
1) Is it so in my setup that when SSIS runtime executes the sequence container it creates a transaction in the beginning of the sequence container and commits the transaction in the end of the sequence container? And in my setup the Execute SQL tasks in the sequence containar are executed under the same transaction?
2) I have a problem that the second query sometimes gives this error:"ErrorCode: -1073548784. ErrorDescription: Executing the query "XXXXX" failed with the following error: "Transaction (Process ID 73) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly."
The 1st query has locked the row for the transaction. How can the second query be deadlocked, shouldn't the transaction have a lock on the row? I'd understand if the 1st query failed sometimes, but don't understand how the 2nd quey can fail.
r,
JM
View 3 Replies
View Related
Jan 3, 2008
Hii Folks
This is my Table Order(OrderNo, CartID, TotalAmount, Name, City, Email, Zip, Date), Then I have my code which I need to insert data into database, but OrderNo is automatically inserted
this is my code, but when I run it it shows the error page, if I remove the direction to my error page, it does not show anything and I don't see any error, could any one check for it please
Imports System
Imports System.Data.SqlClientPartial Class Checkout
Inherits System.Web.UI.PageProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadAmountLabel.Text = Session("OrderTotal").ToString()
SessionLabel.Text = Session.SessionID.ToString()
End SubProtected Sub ContinueButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ContinueButton.Click
Dim shopp As New SqlDataSource()shopp.ConnectionString = ConfigurationManager.ConnectionStrings("SHOESConnectionString").ConnectionString
shopp.InsertCommandType = SqlDataSourceCommandType.Text
shopp.InsertCommand = "INSERT INTO Order(CartID, TotalAmount, Name, City, Email, Zip, Date) VALUES (@CartID, @TotalAmount, @Name, @City, @Email, @Zip, @Date)"shopp.InsertParameters.Add("CartID", SessionLabel.Text)
shopp.InsertParameters.Add("TotalAmount", AmountLabel.Text)shopp.InsertParameters.Add("Name", NameTextBox.Text)
shopp.InsertParameters.Add("City", CityTextBox.Text)shopp.InsertParameters.Add("Email", EmailTextBox.Text)
shopp.InsertParameters.Add("Zip", ZipTextBox.Text)shopp.InsertParameters.Add("Date", DateTime.Now()) Dim rowaffected As Integer = 0
Try
rowaffected = shopp.Insert()Catch ex As Exception Server.Transfer("ErrorPage.aspx")
End Try
shopp = Nothing
If rowaffected <> 1 ThenServer.Transfer("ErrorPage.aspx")
ElseServer.Transfer("success_shopping.aspx")
End IfEnd Sub
End Class
View 6 Replies
View Related
Jan 7, 2008
Finding myself in a bit of a lull at work, I'm trying to create some template packages / solutions, encapsulating some of the best practices that get discussed on here.
I'm thinking about passing configurations from Parent to Child packages, something we all must do on a regular basis. I've always done this a particular way, without thinking too much about it, but I'm not sure if this way is the best. I'd be interested in your opinions.
Scenario:
Parent.dtsx calls Child1.dtsx, Child2.dtsx etc, using Execute Package Task.
Parent has variable Source, and variable Destination, populated from a configuration (my preference is SQL table, but whatever).
These variables are ultimately used to populate the ConnectionString property of the source and destination Connection Managers of the Child packages.
Here's the question: Is it better for the Child packages to look up to their parent, and inherit the values of these variables through Parent Package Configurations, or to look directly to the configuration, and pick them up from there? Or does it not matter?
I tend to assign lots and lots of variables in Parent.dtsx, and pull them down into Child.dtsx with Parent Package Configs, but I'm thinking "is this good/bad/unimportant?"
View 7 Replies
View Related
Jul 21, 2004
I have another question guys I need to send reports to different departments using sql. would this be the xp_sendmail function in sql. Can this be made into a stored procedure? What I'm going to do is make some reports which will constantly be updated with a query. These reports need to be emailed to differnt departments every 2 weeks. Is there a trigger or stored procedure I can setup through sql to do this? Does that make any sense??
View 8 Replies
View Related
Sep 14, 2004
Minimum Date in DateStamp field is not 1-Jan-100. Wouldn't we expect that.
In SQLServer2000 is it "1-Jan-100", if not WHY ??,
In the previous versions it is "01-Jan-1753"
bikramjeet
View 3 Replies
View Related
Feb 2, 2007
Hey,
I have a asp.net 2.0 app that has a sql server express backend. I have been scratching my head for weeks trying to find a good wasy to encrypt my connection string. I store the string in web.config (which in itself is in theory "safe" because it's not servable) and I have scoured the web to try to find a simple way to encrypt the connection string. Even using user store would require running aspreg_iis.exe on the host with a command prompt (which clearly I cannot do). It seems that everyone's solution requires running a command prompt executable on the server.
So I am left to wonder what everyone else does. I am not comfortable using just the web.config because a determined hacker could get to that info. Then again, a determined hacker could get into any system , I guess. There are no credit card #'s stored in this app, but in theory there must be a way. I run all access to the db through stored procedures with permissions, for whatever it's worth.
Thanks in advance!
David
View 3 Replies
View Related
Nov 15, 2007
Why don't you folks (SQL SERVER Management Studio Team or SQL SERVER Database Engine Team) provide an option by using which I would be in a position to know what all the other objects are depended on a selected object and vice versa. That means:
When I select a Table within the SQL SERVER Management Studio if there is an option for understanding "Which all the objects (tables or views) it is depended on (I mean Foreign key and etc... kind of relations) and also Which all the objects (Tables, Views, Stored Procedures and etc...) are using this table", It would be of great help for all developers.
I can be contacted over kotis@microsoft.com
I BLOG @ http://blogs.msdn.com/kreddy
View 3 Replies
View Related
Mar 9, 2005
I need some help to under stand when the right time is for NOLOCK. I work in a small dev group and NOLOCK seams to be a buzz word and others are throwing it in all over for no apparent reason.
I read the thing from http://www.sql-server-performance.com/ and I am sure that our web and SQL servers are about 100x over sized for the application. While are ASP.Net (VB) app may demonstrate some hesitation from time to time I am more inclined to blame poor VB.Net coding techniques before slow SQL. The point being the NOLOCK is being added to SELECTS that are not part of a transaction and were using the SQL data adapter to return datasets or single column values.
Also I am not even sure it’s being used correctly. The OLM has the example:
SELECT au_lname FROM authors WITH (NOLOCK)
However I am seeing it formatted like this:
SELECT au_lname FROM authors (NOLOCK)
I am by no mean an expert, I follow what I read in books or from examples from others. And I have never read in a book go crazy with NOLOCK because it’s the bomb!
Any thoughts? I am trying to learn as much as I can before I raise my hand and say this might be a bad idea.
Thanks
View 4 Replies
View Related
Jan 29, 1999
Other than "dirty" reads, what are the cons of using NOLOCK throughout a query?
View 1 Replies
View Related
Mar 7, 2001
Hi,
I have a job that runs 3 seperate DTS packages.
The first step imports a file and runs successfully.
The second step which is the 2nd DTS package is hanging in the execute mode until I manually stop the job. Apparently,We discovered a bulk insert that is blocking a select statement--both proccesses are within this second DTS package. I tried using the WITH (UNLOCK) on the tables but this DTS package is still failing.
Does anyone have any suggestion? It would be greatly appreciated.
View 1 Replies
View Related
Mar 4, 2004
Hi guys,
I am a new user for DB2.
In DB2 V8, i have a table with some no of columns.
table test
col1
col2
col3
col4
Now i want to issue a query like this.
select col1 from test with(NOLOCK) where col1 = <some value>
when i am executing this query on that time i am getting a error message like this...
SQL0158N The number of columns specified for "MT.TEST" is not the
same as the number of columns in the result table. SQLSTATE=42811
Anyone can help me???
i tried to find out.
I did the same thing with SQL server 2000.
I am not facing any problem there.
Thanks & Regards,
Muthu
View 1 Replies
View Related
Jun 6, 2006
Paul Randal,
There has been a discussion/debate going on this thread about the benefits and drawbacks of using the NOLOCK hint:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=67294
It occurred to me that you might know more about this than any of us, or at least be able to point us to a white paper or knowledge base article that explains the subject in more detail. Any light you can shed on the subject would be a big help.
CODO ERGO SUM
View 1 Replies
View Related
Jan 8, 2008
is really helpful use "with (nolock)" sentence in selects??
100% useful?? disadvantages?
best regards
Joseph
View 4 Replies
View Related
Jun 2, 1999
Hello,
Does anyone know if you place NOLOCK after a view in a select statement, if the effects trickle down to the tables in the view? Or does one have to add NOLOCK to each table within the view?
Thanks
View 1 Replies
View Related
Jun 23, 2004
Hello !!
I'm using the sentence NOLOCK for selects, but I have many sentences, Is there any way to set a parameter in the DBMS, to use NOLOCK parameter by default ???? I mean, I don't like to lock any table for selects.
Is It possible ???? How to do It (step by step) ?
Thanks !!
View 13 Replies
View Related