SELECT a.col1,b.col2,c.col3
FROM tab1 a WITH (UPDLOCK) , tab2 b, tab3 c
WHERE a.col1 = b.col1
and b.col2 = c.col1
WIll the above cause a UPDLOCK on tab1 and not tab2 and tab3?
COmments,thoughts,criticisms?
I have a problem with a query that performs a multi-table join
to get column values and then one of the tables in the join is
being updated. I am getting DEADLOCKs and was wondering if I could
try and reduce that.
Also how can I find out what locks are in effect for a certain
query..Is it syslocks or are there any other tables..?
I am working on a report for a client and in the parameter field they would like to be able to use different date ranges if needed. The fields they would like to have parameters for would be Effective Date, Tracking Date, ReCred Letter Sent Date, ReCred Complete Date. Instead of making 4 different reports, I was looking for something I can put in my statement so she can pull either fields.
This is what I thought would work. I am using Microsoft Visual studio. If you think it is better for me to put it in my actual SQL I can do that too.
Here is what I was doing below. The when I try and run the report, it tells me that I need to have a value in each one of my parameters. Can this type of formula work or do I need to have 4 separate reports.
([Tracking Thru Date] >= @trackfrom) AND ([Tracking Thru Date] <= @trackthru) or ([Effective Date] >= @efffrom) AND ([Effective Date] <= @effthru)or ([ReCred Letter Sent Date] >= @sentfrom) AND ([ReCred Letter Sent Date] <= @sentthru) or ([ReCred Complete Date] >= @compfrom) AND ([ReCred Complete Date] <= @thru)
Greetings:I am trying to conceive what risks might be created by runningmultiple SQL servers within a domain under a single domain account, asopposed to 1) running under the local service account or 2) multipledomain service accounts.In this case, all the SQL servers are SQL2000 running on Win2003. Theservice account is assigned only to the "Domain Users" group.We do use linked server calls, and I have played and suceeded gettingKereberos up to avoid double hop issues when using Windows Auth. Infact, this is one of the reasons that sparked the question in my mind-- in all the MS Kerebos SQL<->SQL examples, the SQL servers run undera unique service account.As an aside, most of the servers are "line of business" servers, butHR runs under a unique server with more sensitive information. I don'treally think that merits a seperate service account, but again, Icould well be missing something.I mostly looking for food for thought, but concrete examples ofgotchas would be appreciated.Thanks all.d.
connection 1. one does select max(grp) from orv and one does select max(grp) from orh. orh is the historical file from orv. We did this to know which is the greather grp between these 2 files. After having did this, we add 1 at grp field. we insert into orv the record max(grp) + 1
connection 2. an other application could insert at the same time record in this table orv with same parameters.
my problem is the following. I need to block record in orv table either on the select ( connection 1) or Insert ( connection 2) to avoid having select max(grp) + 1 on orv at connection 1 and Insert a record into orv at connection 2. I believe I need to use HOLDLOCK, UPDLOCK. but I have not the habitude to use them.
Can I do this ? connection 1 select max(grp) from orv WITH HOLDLOCK connection 2 what should I use to avoid lock when I need to insert into orv. ?
Is there anything I can do from the Enterprise Manager console or fromwithin a JDBC connection to achieve the same effect as WITH(UPDLOCK)?Yes, I could change all of my SQL statements to include the lock... butisn't there any way to set or tweak something in SQL Server so that I won'thave to hack a lot of code* to make things concurrent? Perhaps a way to setUPDLOCK as the default behaviour for the server, or schema, or table, orsomething?Jerry H.* == The existing SQL has to remain as generic as possible so that it can beimplemented for four other databases.
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.
I was writing a query using both left outer join and inner join. And the query was ....
SELECT S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname FROM Production.Suppliers AS S LEFT OUTER JOIN (Production.Products AS P INNER JOIN Production.Categories AS C
[code]....
However ,the result that i got was correct.But when i did the same query using the left outer join in both the cases
i.e..
SELECT S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname FROM Production.Suppliers AS S LEFT OUTER JOIN (Production.Products AS P LEFT OUTER JOIN Production.Categories AS C ON C.categoryid = P.categoryid) ON S.supplierid = P.supplierid WHERE S.country = N'Japan';
The result i got was same,i.e
supplier country productid productname unitprice categorynameSupplier QOVFD Japan 9 Product AOZBW 97.00 Meat/PoultrySupplier QOVFD Japan 10 Product YHXGE 31.00 SeafoodSupplier QOVFD Japan 74 Product BKAZJ 10.00 ProduceSupplier QWUSF Japan 13 Product POXFU 6.00 SeafoodSupplier QWUSF Japan 14 Product PWCJB 23.25 ProduceSupplier QWUSF Japan 15 Product KSZOI 15.50 CondimentsSupplier XYZ Japan NULL NULL NULL NULLSupplier XYZ Japan NULL NULL NULL NULL
and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.
The benifit of UPDLOCK is that it avoids deadlock in case both sessions run the below query at the same time.The table has clustered index on ID column
----session 1 -------- begin transaction select * from a1
update a1 set id = 22 where id = 2
----session 2 -------- begin transaction select * from a1
update a1 set id = 22 where id = 2
Now to avoid deadlock in the above scenario we should use (UPDLOCK) hint in the select statement.Now my question is that deadlock will be avoided in this case when both the sessions use UPDLOCK hint. If only one session uses UPDLOCk and other does not then there will be deadlock .For example session 1 uses UPDLOCK hint this will hold the U lock on the row, but the session 2 does not use this hint and apply shared lock on the same row. Now there will be deadlock when session 1 tries to update the record and is blocked by shared locks of session 2. same will be the case with session 2 and both will wait for each other and hence dead lock.so what steps can be taken to avoid deadlocks in this case. I do not want to use Snapshot isolation.
This article instructed me on how to process rows from a table used as a data queue for multiple processes.
http://www.mssqltips.com/tip.asp?tip=1257
I tested this against the AdventureWorks DB (SQL 2005) and multiple SQL connections inside of Sql Mgmt. Studio).
Connection1:
BEGIN TRANSACTION
SELECT TOP 1 * FROM Production.WorkOrder WITH (updlock, readpast) --skips over locked rows --COMMIT TRANSACTION
Connection2:
BEGIN TRANSACTION
SELECT TOP 1 * FROM Production.WorkOrder WITH (updlock, readpast) --skips over locked rows
COMMIT TRANSACTION
This works like I want where connection 2 skips over the locked row from connection 1 and gets the next available record from the table / queue. However, when I add ORDER BY tsql to each sql statement, connection 2 is now blocked waiting for Connection 1 to commit. (This is not what I want)
Connection1:
BEGIN TRANSACTION
SELECT TOP 1 * FROM Production.WorkOrder WITH (updlock, readpast) order by DueDate
--COMMIT TRANSACTION
Connection2:
BEGIN TRANSACTION
SELECT TOP 1 * FROM Production.WorkOrder WITH (updlock, readpast) order by DueDate --is blocked until connection 1 commits transaction
COMMIT TRANSACTION
How do I prevent blocking when using these locking hints with ORDER BY?
I'm having trouble with a multi-table JOIN statement with more than one JOIN statement.
For each order, I need to return the following: CarsID, CarModelName, MakeID, OrderDate, ProductName, Total ordered the Car Category.
The carid (primary key) and carmodelname belong to the Cars table. The makeid and orderdate belong to the OrderDetails table. The productname and carcategory belong to the Product table.
The number of rows returned should be the same as the number of rows in OrderDetails.
I have table 'stores' that has 3 columns (storeid, article, doc), I have a second table 'allstores' that has 3 columns(storeid(always 'ALL'), article, doc). The stores table's storeid column will have a stores id, then will have multiple articles, and docs. The 'allstores' table will have 'all' in the store for every article and doc combination. This table is like the master lookup table for all possible article and doc combinations. The 'stores' table will have the actual article and doc per storeid.
What I am wanting to pull is all article, doc combinations that exist in the 'allstores' table, but do not exist in the 'stores' table, per storeid. So if the article/doc combination exists in the 'allstores' table and in the 'stores' table for storeid of 50 does not use that combination, but store 51 does, I want the output of storeid 50, and what combination does not exist for that storeid. I will try this example:
'allstores' 'Stores' storeid doc article storeid doc article ALL 0010 001 101 0010 001 ALL 0010 002 101 0010 002 ALL 0011 001 102 0011 002 ALL 0011 002
So I want the query to pull the one from 'allstores' that does not exist in 'stores' which in this case would the 3rd record "ALL 0011 001".
I am using stored procedure to load gridview but problem is that i am not getting all rows from first table[ Subject] on applying conditions on second table[ Faculty_Subject table] ,as you can see below if i apply condition :-
Faculty_Subject.Class_Id=@Class_Id
Then i don't get all subjects from subject table, how this can be achieved.
Sql Code:- GO ALTER Proc [dbo].[SP_Get_Subjects_Faculty_Details] @Class_Id int AS BEGIN
If I join Table1 to Table2 with a WHERE condition, isit the same if I would join Table2 to Table1 consideringthat the size of the tables are different.Let's assume Table2 is much bigger than Table1.I've never used MERGE, HASH JOINs etc, do any ofthese help in this scenario?Thank you
Is it possible to insert data into a table from a temporary table that is inner join? Can anyone share an example of a stored procedure that can do this? Thanks, xyz789
Hi there. I haven't been able to figure out how to join a table on column on multiple table names. Here's the situation:
I have a table "tblJob" with a key of jobID. Now for every jobID, the program creates a new table that keeps track of the stock before the jobId was processed and after it was processed to give accurate stock levels and show the difference in stock levels. So, a jobID of 355 would be related to the table: "tblPreStock_335" and "tblPostStock_335". These 2 tables have all the materials in stock and the quantity. Therefore they show how much material was used. I need to figure out the difference in the material in the stock before and after the processing.
That means that I have to get a stockID, get the associated pre and post tables, and then display the difference of ALL the materials in the pre and post tables.
Could someone help me get started on the right path? Even a link to similiar problem that I haven't found would be nice.
I have one main Table "MainTable" which I want to relate with "subTable1, subTable2, ..." in such a way that:
"ith subTable" have to be related/joind on "ith row" of the "MainTable", "jth subTable" have to be related/joined on "jth row" of the "MainTable" and so on...
What I want Actually?
I want that when ever I delete a Record in the "MainTable", The corresponding "subTable" have to be deleted Itself.
I thought a solution that, I can cerate a Trigger on Delete of the "MainTable" and it would delete the corresponding "subTable". But I dont know how to ceate that.
Secound solution what I thought is, that may be there is some majic power in the Table Joinings. That I might join "MainTable" row with "subTable" ( ofcourse that I dont know either :))
So my question is, that what is the actual solution for my problem?
What ever solution is please give me a sample also with that. Like in a Trigger how can I write some Expression which can delete the "subTable" for the Currunt delete Row.
Here's my issue. I've got a series of tables like so: dbo.CustomerBobJones dbo.CustomerJaneDoe dbo.CustomerBrianSmith
Each contains these columns: DateOfComment datetime CommentText varchar(200)
Now all other customer information is stored in another table dbo.CustomerList CustomerID int CustomerName varchar(50) Address varchar(50) and so on.
I need to join from this customer list to the individual tables for those customers.
My thought was to add to dbo.CustomerList the name of the table associated to that account... but I'm not sure once that information is entered how I'll be able to join between them.
I had thought that the id in sysobjects might be the key but I'm not sure how to join using an id instead of a table name.
Orders, with OrderID as primary key, a code for the client, and a code for the place of delivery/receipant.
Both the client and place of delivery should be linked to the table:
Relations, where each relation has it's own PrimaryID which is a auto-numbered ID. Now I want to substract my orders, with both the clientcode, and the place of delivery code linked to the relations table, so that for both the name and adress is shown.
I can link one of them by:
InnerJoin On Orders.ClientID = Relations.ClientID, but it's not possible to also link to the ReceipantsID. Is there a way to solve this?
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 )?
I am attempting to join 2 table variables on 2 keys, employeeID and employerID
SELECT * FROM @employees INNER JOIN @addresses ON ((@employees.employeeID = @addresses.employeeID) AND (@employees.employerID = @addresses.employerID))
Both tables are declared with proper fields and they are populated with the correct data; I get this error msg upon execution.
Server: Msg 137, Level 15, State 2, Line 28 Must declare the variable '@employees'.
All, I have two tables, A and B. Table A has names, address, phone. Table B has names and image filename. Table A and B can be linked by names. I would like to show all the names in Table A and link to Table B such that it will show a column image filename if there is a image filename. If the name cannot be found in the Table B display a NULL on the column. (Note : there may be two same names in the Table B, so how can i show only the first image filename).
Im trying to write a SQL statement that will join 2 tables based on a customer has 2 specific products. eg.
Table 1: Customer
MemberID MemberName Email ect
Table 2: Products
ProductID MID (MemberID of table 1) ProductName
So how do i write a sql statement to only bring up say cutomers that have a ProductName of "Computers" AND "Laptops" They must have both Computers as an entry in the products table and an entry of Laptops in the relational database.
I am trying to join 5 tables in a sql server 2k db. Does anyone know of a good set of guidelines for doing this? Alternately, could someone find the problem in the following query?
The query that I am using is listed here (please let me know if I am violating any programming guidelines on this):
SELECT p.ParticipantID, pr.Age, ir.FnlTime, e.EventDate FROM Participant p INNER JOIN PartRace pr ON p.ParticipantID = pr.ParticipantID JOIN IndResults ir ON pr.ParticipantID = ir.ParticipantID JOIN RaceData rd ON ir.RaceID = rd.RaceID JOIN Events e ON e.EventID = rd.EventID WHERE rd.Dist = '5_km' AND p.Gender = 'm' AND ir.FnlTime <> '00:00' AND e.EventGrp = 1 ORDER BY ir.ParticipantID
The problem that I am having is that if a participant shows up multiple times (which they could do since this is designed to get the performances for an event over a series of years) it does not associate the correct data from year to year. Basically some times show up where they shouldn't.
HTML Code: comid companyname parentcompany maincom ------- ----------- -------------- 1 test 0 1 2 testxx 1 0
So here the second record i have parent company = 1 meaning company test as parent for textxx , if a company has parentcompany as 0 means tat has no parent company.
So in this i need have a result to display in grid is
HTML Code: companyname parentcompany test no testxx test
I tired with inner join , but it is only select the second record as it's skip the first record due inner join with comid .