Asking for some sample SQL/SP code to perform updates/deletes with joinedtables.Example 1:For every record that is matched on both tables A and B, update a field intable A.Example 2:For every record that is matched on both tables A and B, delete record intable A.TIA.~ Duane Phillips.
What is wrong in this query am getting incorrect syntax near ','.error. I am using sql server 2014
DELETE ab, b FROM Authors AS a INNER JOIN AuthorArticle AS ab ON a.AuthID=ab.AuthID INNER JOIN Articles AS b ON ab.ArticleID=b.ArticleID WHERE AuthorLastName='Tom';
We find that a delete command on a table where the rows to be deleted involve an inner join between the table and a view formed with an outer join sometimes works, sometimes gives error 625.
If the delete is recoded to use the join key word instead of the = sign then it alway gives error 4425.
625 21 0 Could not retrieve row from logical page %S_PGID by RID because the entry in the offset table (%d) for that RID (%d) is less than or equal to 0. 1033 4425 16 0 Cannot specify outer join operators in a query containing joined tables. View '%.*ls' contains outer join operators. The delete with a correleted sub query instead of a join works.
Error 4425 text would imply that joins with view formed by outer joins should be avoided.
SQL Server 2000Howdy All.Is it going to be faster to join several tables together and thenselect what I need from the set or is it more efficient to select onlythose columns I need in each of the tables and then join them together?The joins are all Integer primary keys and the tables are all about thesame.I need the fastest most efficient method to extract the data as thisquery is one of the most used in the system.Thanks,Craig
Why is it that SQL joins (*=) run a little faster as opposed to ANSI joins(LEFT JOIN...)? Aren't they supposed to be almost identical?
The issue is this: we are promoting using ANSI syntax for the obvious reason (future versions of SQL Server may not support SQL Server syntax; portability, etc.)
However, the problem is the speed. What have others done about this? Do you use ANSI syntax or SQL syntax? HOw true is it that future SQL Server versions may discontinue support for the '*=" and "=*' join operators.
I have four tables which I want to return results for an advanced search function, the tables contain different data, but can be quite easily joined,
Table A Contains a Main Image, this image is displayed in the results Table B Contains an Icon, this image is displayed in the results Table C doesn't have an image in it but has a child table with a number of images associated to the table, in the UNION ALL statement I would Like to do a Join to get say the top Image from this child and print it for the row associated with table C.
Select title, description, image from tableA UNION ALL Select title, description, icon as image from tableB UNION ALL title, description, ( inner Join SELECT top(1) from imageTableC where imagetableC.FK = tableC.PK) as image from tableC
Could someone show me the syntax to do this, I have all the information printing to the screen, bar this table C image.
Im having a problem with a statement i cannot seem to get 2 left joins working at the same time 1 works fine but when i try the second join i get this error:-
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'children_tutorial.school_id=schools.idx LEFT JOIN regions ON children_tutorial.region_id=region.idx'.
My SQL statment is as follows :- SELECT children_tutorial.*,schools.schoolname,regions.rname FROM children_tutorial LEFT JOIN schools ON children_tutorial.school_id=schools.idx LEFT JOIN regions ON children_tutorial.region_id=region.idx
I am using an Access database i have tried all sorts to get it working and its driving me mad!! any help would be really appreciated.
I have some simple files but they are failing because the delete history task is failing as it is looking for files in a non existent directory.
It is looking for files in C:Program FilesMicrosoft SQL ServerMSSQL10_50.INSTANCEMSSQLLog whereas it should be looking in C:Program FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLLog
how I can get this corrected so I can get the Maintenance Plans to run correctly.
I have tried deleting and recreating the Plan but to no avail
I am using Master Data Service for couple of months now. I can load, update, merge and soft delete data in MDS. Occasionally we even have to hard delete data from MDS. If we keep on soft deleting records in a MDS table eventually there will be huge number of soft deleted records. Is there an easy way to hard delete all the soft deleted records from all MDS tables in a specific Model.
Background: Am working on completing an ORM that can not only handles CRUD actions -- but that can also updates the structure of a table transparently when the class defs change. Reason for this is that I can't get the SQL scripts that would work for updating a software on SqlServer to be portable to other DBMS systems. Doing it by code, rather than SQL batch has a chance of making cross-platform, updateable, software...
Anyway, because it needs to be cross-DBMS capable, the constraints are that the system used must work for the lowest common denominator....ie, a 'recipe' of steps that will work on all DBMS's.
The Problem: There might be simpler ways to do this with SqlServer (all ears :-) - just in case I can't make it cross platform right now) but, with simplistic DBMS's (SqlLite, etc) there is no way to ALTER table once formed: one has to COPY the Table to a new TMP name, adding a Column in the process, then delete the original, then rename the TMP to the original name.
This appears possible in SqlServer too --...as long as there are no CASCADE operations. Truncate table doesn't seem to be the solution, nor drop, as they all seem to trigger a Cascade delete in the Foreign Table.
So -- please correct me if I am wrong here -- it appears that the operations would be along the lines of: a) Remove the Foreign Key references b) Copy the table structure, and make a new temp table, adding the column c) Copy the data over d) Add the FK relations, that used to be in the first table, to the new table e) Delete the original f) Done?
The questions are: a) How does one alter a table to REMOVE the Foreign Key References part, if it has no 'name'. b) Anyone know of a good clean way to get, and save these constraints to reapply them to the new table. Hopefully with some cross platform ADO.NET solution? GetSchema etc appears to me to be very dbms dependant? c) ANY and all tips on things I might run into later that I have not mentioned, are also greatly appreciated.
I am having great difficulty with cascading deletes, delete triggers and referential integrity.
The database is in First Normal Form.
I have some tables that are child tables with two foreign keyes to two different parent tables, for example:
Table A / Table B Table C / Table D
So if I try to turn on cascading deletes for A/B, A/C, B/D and C/D relationships, I get an error that I cannot have cascading delete because it would create multiple cascade paths. I do understand why this is happening. If I delete a row in Table A, I want it to delete child rows in Table B and table C, and then child rows in table D as well. But if I delete a row in Table C, I want it to delete child rows in Table D, and if I delete a row in Table B, I want it to also delete child rows in Table D.
SQL sees this as cyclical, because if I delete a row in table A, both table B and table C would try to delete their child rows in table D.
Ok, so I thought, no biggie, I'll just use delete triggers. So I created delete triggers that will delete child rows in table B and table C when deleting a row in table A. Then I created triggers in both Table B and Table C that would delete child rows in Table D.
When I try to delete a row in table A, B or C, I get the error "Delete Statement Conflicted with COLUMN REFERENCE". This does not make sense to me, can anyone explain? I have a trigger in place that should be deleting the child rows before it attempts to delete the parent row...isn't that the whole point of delete triggers?????
This is an example of my delete trigger:
CREATE TRIGGER [DeleteA] ON A FOR DELETE AS Delete from B where MeetingID = ID; Delete from C where MeetingID = ID;
And then Table B and C both have delete triggers to delete child rows in table D. But it never gets to that point, none of the triggers execute because the above error happens first.
So if I then go into the relationships, and deselect the option for "Enforce relationship for INSERTs and UPDATEs" these triggers all work just fine. Only problem is that now I have no referential integrity and I can simply create unrestrained child rows that do not reference actual foreign keys in the parent table.
So the question is, how do I maintain referential integrity and also have the database delete child rows, keeping in mind that the cascading deletes will not work because of the multiple cascade paths (which are certainly required).
I'm trying to clean up a database design and I'm in a situation to where two tables need a FK but since it didn't exist before there are orphaned records.
Tables are:
Brokers and it's PK is BID
The 2nd table is Broker_Rates which also has a BID table.
I'm trying to figure out a t-sql statement that will parse through all the recrods in the Broker_Rates table and delete the record if there isn't a match for the BID record in the brokers table.
I know this isn't correct syntax but should hopefully clear up what I'm asking
this is my Delete Query NO 1 alter table ZT_Master disable trigger All Delete ZT_Master WHERE TDateTime> = DATEADD(month,DATEDIFF(month,0,getdate())-(select Keepmonths from ZT_KeepMonths where id =1),0) AND TDateTime< DATEADD(month,DATEDIFF(month,0,getdate()),0) alter table ZT_Master enable trigger All
I have troble in Delete Query No 2 here is a select statemnt , I need to delete them select d.* from ZT_Master m, ZT_Detail d where (m.Prikey=d.MasterKey) And m.TDateTime> = DATEADD(month,DATEDIFF(month,0,getdate())-(select Keepmonths from ZT_KeepMonths where id =1),0) AND m.TDateTime< DATEADD(month,DATEDIFF(month,0,getdate()),0) I tried modified it as below delete d.* from ZT_Master m, ZT_Detail d where (m.Prikey=d.MasterKey) And m.TDateTime> = DATEADD(month,DATEDIFF(month,0,getdate())-(select Keepmonths from ZT_KeepMonths where id =1),0) AND m.TDateTime< DATEADD(month,DATEDIFF(month,0,getdate()),0) but this doesn't works..
can you please help? and can I combine these 2 SQL Query into one Sql Query? thank you
I'm using SqlDataSource and an Access database. Let's say I got two tables:user: userID, usernamemessage: userID, messagetextLet's say a user can register on my website, and leave several messages there. I have an admin page where I can select a user and delete all of his messages just by clicking one button.What would be the best (and easiest) way to make this?Here's my suggestion:I have made a "delete query" (with userID as parameter) in MS Access. It deletes all messages of a user when I type in the userID and click ok.Would it be possible to do this on my ASP.net page? If yes, what would the script look like?(yes, it is a newbie question)
The requirement is: I should allow single row delete from a table but not bulk delete. An audit table should get updated if there is any single delete or single update. So I wrote the triggers as follows: for single and bulk delete
ALTER TRIGGER [dbo].[TRG_Delete_Bulk_tbl_attendance] ON [dbo].[tbl_attendance] AFTER DELETE AS
[code]...
When I try to run the website, the database error I am getting is:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 0, current count = 1.
I ran the following query in Query Analyzer on a machine running SQL Server 2000. I'm attempting to delete from a linked server running SQL Server 2005:
DELETE FROM sql2005.production.dbo.products WHERE vendor='Foo' AND productId NOT IN ( SELECT productId FROM sql2000.staging.dbo.fooProductList )
The status message (and @@ROWCOUNT) told me 8 rows were affected, but nothing was actually deleted; when I ran a SELECT with the same criteria as the DELETE, all 8 rows are still there. So, once more I tried the DELETE command. This time it told me 7 rows were affected; when I ran the SELECT again, 5 of the rows were still there. Finally, after running this exact same DELETE query 5 times, I was able to remove all 8 rows. Each time it would tell me that a different number of rows had been deleted, and in no case was that number accurate.
I've never seen anything like this before. Neither of the tables involved were undergoing any other changes. There's no replication going on, or anything else that should introduce any delays. And I run queries like this all day, involving every thinkable combination of 2000 and 2005 servers, that don't give me any trouble.
Does anyone have suggestions on what might cause this sort of behavior?
I have a problem with one report on my server. A user has requested that I exclude him from receiving a timed email subscription to several reports. I was able to amend all the subscriptions except one. When I try to remove his email address from the subscription I receive this error:
An internal error occurred on the report server. See the error log for more details. (rsInternalError) Get Online Help
For more information about this error navigate to the report server on the local server machine, or enable remote errors
Online no help couldn't offer any advice at all, so I thought I'd just delete the subscription and recreate it again, but I receive the same message. "Okay, no problem, I'll just delete the report and redeploy it and set up the subscription so all the other users aren't affected", says I. "Oh, no!", says the report server, and then it give me this message:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Data.SqlClient.SqlException: Only members of sysadmin role are allowed to update or delete jobs owned by a different login. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Microsoft.ReportingServices.Library.InstrumentedSqlCommand.ExecuteNonQuery() at Microsoft.ReportingServices.Library.DBInterface.DeleteObject(String objectName) at Microsoft.ReportingServices.Library.RSService._DeleteItem(String item) at Microsoft.ReportingServices.Library.RSService.ExecuteBatch(Guid batchId) at Microsoft.ReportingServices.WebServer.ReportingService2005.ExecuteBatch() --- End of inner exception stack trace ---
What's even weirder is that I'm the owner and creator of the report and I'm a system admin and content manager on the report server and I set up the subscription when the report was initially deployed. Surely I should have sufficient rights to fart around with this subscription/report as I see fit?
I have rebooted the server, redeployed the report, checked credentials on the data source and tried amending and deleting from both the report manager and management studio but still I am prevented from doing so.
This one is weird and I am missing something fundamental on this one. A developer was getting a timeout with this...
CREATE PROCEDURE p_CM_DeleteBatch ( @SubmitterTranID VARCHAR(50) ) AS DECLARE @COUNT INT, @COMMIT INT
SET @COUNT = 0 SET @COMMIT = 1 --DO NOT CHANGE THIS. The Operation will be commited only when this value is 1
select @COUNT = COUNT(*) from claimsreceived where (claimstatus NOT IN ('Keyed', 'Imported')) AND SubmitterTranID = @SubmitterTranID
IF (@COUNT = 0) --This means that that Claims under this Batch have not been adjudicated & it is safe to delete BEGIN BEGIN TRANSACTION DELETE FROM INVOICECLAIMMAPPING WHERE CLMRECDID IN (SELECT DISTINCT CLMRECDID FROM CLAIMSRECEIVED WHERE SUBMITTERTRANID = @SUBMITTERTRANID) IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsPayment WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsPaymentServices WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsreceivedPayorServices where ClmRecdPyID in (SELECT ClmRecdPyID FROM ClaimsReceivedPayors WHERE SubmitterTranID = @SubmitterTranID)
IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsReceivedPayors WHERE ClmRecdid in (SELECT ClmRecdID FROM ClaimsReceived WHERE SubmitterTranID = @SubmitterTranID) IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsReceivedServices WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0 DELETE FROM ClaimsReceived WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0 DELETE FROM BATCHLOGCLAIMS WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
IF (@COMMIT = 1) BEGIN --ROLLBACK TRANSACTION --For Testing Purpose ONLY COMMIT TRANSACTION RETURN (0) END ELSE BEGIN ROLLBACK TRANSACTION RETURN (-1) END END ELSE BEGIN RaisError ('This Batch cannot be deleted. It has claim(s) which has been Adjudicated', 16, 1) END GO
I applied a couple of indices and got ride of the uncorrelated subqueries
CREATE PROCEDURE p_CM_DeleteBatch ( @SubmitterTranID VARCHAR(50) ) AS DECLARE @COUNT INT, @COMMIT INT
SET @COUNT = 0 SET @COMMIT = 1 --DO NOT CHANGE THIS. The Operation will be commited only when this value is 1
select @COUNT = COUNT(*) from claimsreceived where (claimstatus NOT IN ('Keyed', 'Imported')) AND SubmitterTranID = @SubmitterTranID
IF (@COUNT = 0) --This means that that Claims under this Batch have not been adjudicated & it is safe to delete BEGIN BEGIN TRANSACTION
DELETE INVOICECLAIMMAPPING FROM INVOICECLAIMMAPPING JOIN CLAIMSRECEIVED ON INVOICECLAIMMAPPING.CLMRECDID = CLAIMSRECEIVED.CLMRECDID WHERE CLAIMSRECEIVED.SUBMITTERTRANID = @SUBMITTERTRANID
IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsPayment WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsPaymentServices WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE ClaimsreceivedPayorServices FROM ClaimsreceivedPayorServices JOIN ClaimsReceivedPayors ON ClaimsreceivedPayorServices.ClmRecdPyID = ClaimsReceivedPayors.ClmRecPyID WHERE ClaimsReceivedPayors.SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE ClaimsReceivedPayors FROM ClaimsReceivedPayors JOIN ClaimsReceived ON ClaimsReceivedPayors.ClmRecdid = ClaimsReceived.ClmRecdid WHERE ClaimsReceived.SubmitterTranID = @SubmitterTranID
IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsReceivedServices WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM ClaimsReceived WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
DELETE FROM BATCHLOGCLAIMS WHERE SubmitterTranID = @SubmitterTranID IF (@@ERROR <> 0) SET @COMMIT = 0
IF (@COMMIT = 1) BEGIN --ROLLBACK TRANSACTION --For Testing Purpose ONLY COMMIT TRANSACTION RETURN (0) END ELSE BEGIN ROLLBACK TRANSACTION RETURN (-1) END END ELSE BEGIN RaisError ('This Batch cannot be deleted. It has claim(s) which has been Adjudicated', 16, 1) END GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON
GO
Suddenly this constraint was being violated with the change
Is the delete on ClaimsReceivedPayors starting before the delete on ClaimsreceivedPayorServices finishes? If so why would it matter between the join and subquery? This one is making me depressed because I can not explain it.
Need some advice solving a little problem I have with my database!
Current setup:
I have a person table that is made up of 39 columns. I also allow for person records to be deleted but I do this by having another table I call LogicallyDeletedrecords. This table is made up of the PersonId, Reason for deletion/suppression and a date time stamp. To access Live records I created a view based on my Person table which contains a WHERE clause to exclude records that exist in the LogicallyDeletedrecords. Similarly, I have another view DeadPersonData which contains Person records that have been removed. Hope it all makes sense so far! Now on to my worries!
The problem:
My Person table contains 9+ million records. The LogicallyDeletedrecords table has 500k+ but I anticipate further growth over the coming weeks/months. My worry is that my LivePersonData view will be too slow to access as my LogicallyDeletedrecords table grows. What’s more, as part of my Load routine, I have to make sure that Person data loaded on to the system is excluded if that same person exists as a deleted member. Both of these actions could slow down my system as the deleted table grows.
My thoughts:
I’ve been thinking of physically deleting dead Person records from my person table (possibly creating an archive table to hold them). But then if I delete them how do I cross check the details when new Person details get loaded?! As I said, my current LogicallyDeletedrecords table holds the PersonId, ReasonDeleted and CreationStamp. The only way is to add further columns which I use to match Person Details?
there are two tables involve in replication let say table1 and replicated table is also rep.table1.
we are not deleting records physically in table1 so only a bit in table1 has true when u want to delete a record but the strange thing is that replication agaent report that this is hard delete operation on table1 so download and report hard delete operation and delete the record in replicated table which is very crucial.
plz let me know where am i wrong and how i put it into right way.
there is no triggers on published tables and noother trigger is created on published table.
When I add a constraint to the where part of the SQL statement below it will only show the nc_department.department where siteid equals it. How do I pull and display all of those departments regardless of where the siteid = the selected item? In other words doesnt the Left outer Join supposed to grab all contents from the left table regardless?
SQL = "SELECT nc_department.order_id, nc_department.department, Count(nonconformance.department_id) as 'events', ISNULL(SUM(nonconformance.nc_wafer_qty),0) as wafers FROM nc_department LEFT OUTER JOIN nonconformance ON nc_department.department_id = nonconformance.department_id WHERE nc_department.active = '1' AND nonconformance.site_id = '" & siteid.SelectedItem.Value & "' GROUP BY nc_department.department , nc_department.order_id"
Soory if this is a bit basic, but I'm chasing my tail: I have two select statements: SELECT MyRows from Table1 where X = 1 SELECT OtherRows From Table 2 Where y = 3 I want to produce a LEFT JOIN between the result of each query, and return the resultant rows I know this is not correct syntax:
(SELECT MyRows from Table1 where X = 1) LEFT JOIN (SELECT OtherRows From Table 2 Where y = 3) ON Tabel1.Row1 = Table2.Row2
but I think it illustrates what I want to do If I do the WHERE after the join I only get where there is a righthand table I cant get the syntax right, an example with the correct grammar would be very much appreciated
Instead of inserting into, how can I use a join of multiple tables to update a table. This is the join that inserts.
INSERT INTO [table] (MyID, material, dollars) SELECT l.MyID, material, dollars FROM Tab_Client_Input l left outer JOIN Tab_Special_tox r ON l.MyID = r.MyID
Hi Folks, I writing a store procedure, the first three parts work pretty well. The last select statement has about 8 outer joins in it. every time I run the store procedure, I get an error message for the last part. Below are the error message and the store procedure:
Store Procedure:
--Create Procedure dbo.IMS_Donation
--AS
Select Distinct D_VST_ID as 'DRWLOC_ID', D_VST_INSTID as 'DRWLOC_INSTID' Into Donor_Visit1 From DNR_VST_DB_REC Where D_VST_DATE Between 20010101 AND 20040512 AND D_VST_DONTYP in ('AP', 'WB', 'RP', 'E2', 'E1') AND D_VST_STATUS = 'DN' ORDER BY D_VST_ID GO
SELECT DRWLOC_ID as 'COUNT_ID', DRWLOC_INSTID as 'COUNT_INSTID', count(*) as 'COUNT_VISITS' INTO Donor_Visit2 FROM DNR_VST_DB_REC, Donor_Visit1 Where D_VST_ID = DRWLOC_ID AND NOT EXISTS (Select R_DCC_ID From REC_DCC_DB_REC Where R_DCC_ID = DRWLOC_ID AND R_DCC_INSTID = DRWLOC_INSTID AND R_DCC_CALLCD = 'DC') GROUP BY DRWLOC_ID, DRWLOC_INSTID GO
SELECT DVT1.DRWLOC_ID as'COMP_ID', CMP.l_CMP_UNITNO as 'COMP_UNITID', CMP.L_CMP_INSTID as 'COMP_INSTID', count(*) as 'COMP_COMPTOT' INTO Donor_Visit3 FROM LAB_CMP_DB_REC CMP, Donor_Visit1 DVT1, DNR_VST_DB_REC VST, CMP_VST_Jct CVT WHERE CMP.L_CMP_INSTID = DVT1.DRWLOC_INSTID AND VST.D_VST_ID = DVT1.DRWLOC_ID AND VST.D_VST_UNITNO = CVT.L_CMP_UNITNO AND CMP.L_CMP_UNITNO = CVT.L_CMP_UNITNO AND CMP.L_CMP_STATCD != 'MOD' AND CMP.L_CMP_CMPCD NOT IN ('INC', 'EMTY') AND VST.D_VST_DATE BETWEEN 20010101 AND 20040512 AND VST.D_VST_STATUS = 'DN' GROUP BY DVT1.DRWLOC_ID, CMP.L_CMP_UNITNO, CMP.L_CMP_INSTID
GO
SELECT DISTINCT NAM.N_NAM_ID AS 'ID1', NAM.N_NAM_INSTID AS 'INSTID1', NAM.N_NAM_FNAME AS 'FNAME1', NAM.N_NAM_MINITIAL AS 'MINITIAL1', NAM.N_NAM_LNAME AS 'LNAME1', PER.N_PER_BIRTH AS 'BIRTH1', ADR.N_ADR_ADDR1 AS 'ADDR1', ADR.N_ADR_ADDR2 AS 'ADDR2', ADR.N_ADR_CITY AS 'CITY1', ADR.N_ADR_STATE AS 'STATE1', SUBSTRING(ADR.N_ADR_ZIP, 1,5) AS 'ZIP1', PER.N_PER_EMAIL AS 'EMAIL1', PER.N_PER_GENDER AS 'GENDER1', PHNA.N_PHN_AREACD AS 'AREAD1', PHNA.N_PHN_PREFIX AS 'PREFIXD1', PHNA.N_PHN_NUMBER AS 'NBRD1', PHNA.N_PHN_EXTENTN AS 'EXTD1', PHNB.N_PHN_AREACD AS 'AREAD2', PHNB.N_PHN_PREFIX AS 'PREFIXD2', PHNB.N_PHN_NUMBER AS 'NBRE2', PHNB.N_PHN_EXTENTN AS 'EXTD2', BTY.D_BTY_ABO AS 'ABO1', BTY.D_BTY_RHESUS AS 'RHI', VST.D_VST_DATE AS 'FIRST1', DV2.COUNT_VISITS AS 'COUNT', SUM(DTS.D_DTS_DONSUM) AS 'AWARD', ELG.D_ELG_RWBDTE AS 'ELIG1' --INTO Donor_Visit4 From Donor_Visit2 DV2 RIGHT OUTER JOIN DNR_DTS_DB_REC DTS ON DV2.COUNT_INSTID = DTS.D_DTS_INSTID RIGHT OUTER JOIN NAT_PER_DB_REC PER ON DV2.COUNT_INSTID = PER.N_PER_INSTID RIGHT OUTER JOIN DNR_BTY_DB_REC BTY ON DV2.COUNT_INSTID = BTY.D_BTY_INSTID RIGHT OUTER JOIN NAT_PHN_DB_REC PHNA ON DV2.COUNT_INSTID = PHNA.N_PHN_INSTID RIGHT OUTER JOIN NAT_PHN_DB_REC PHNB ON DV2.COUNT_INSTID = PHNB.N_PHN_INSTID RIGHT OUTER JOIN DNR_DTS_DB_REC DNT ON DV2.COUNT_ID = DNT.D_DTS_ID RIGHT OUTER JOIN NAT_PER_DB_REC PER1 ON DV2.COUNT_ID = PER1.N_PER_ID RIGHT OUTER JOIN DNR_BTY_DB_REC BTY1 ON DV2.COUNT_ID = BTY1.D_BTY_ID LEFT OUTER JOIN NAT_PHN_DB_REC PHNA1 ON DV2.COUNT_ID = PHNA1.N_PHN_ID RIGHT OUTER JOIN NAT_PHN_DB_REC PHNB1 ON DV2.COUNT_ID = PHNB1.N_PHN_ID LEFT OUTER JOIN NAT_PHN_DB_REC PHNA2 ON PHNA2.N_PHN_PHTYP = 'D' LEFT OUTER JOIN NAT_PHN_DB_REC PHNB2 ON PHNB2.N_PHN_PHTYP = 'E', --LEFT OUTER JOIN DNR_DTS_DB_REC DTS1 --DTS1.D_DTS_CNTTYP <> 'N', DNR_ELG_DB_REC ELG, NAT_NAM_DB_REC NAM, NAT_ADR_DB_REC ADR, DNR_VST_DB_REC VST WHERE DV2.COUNT_INSTID = VST.D_VST_INSTID AND DV2.COUNT_INSTID = ELG.D_ELG_INSTID AND DV2.COUNT_INSTID = N_NAM_INSTID AND DV2.COUNT_INSTID = N_ADR_INSTID AND DV2.COUNT_INSTID = VST.D_VST_INSTID --AND DV2.COUNT_INSTID = ELG.D_ELG_ID AND NAM.N_NAM_SEQNO = 0 AND VST.D_VST_DATE = (SELECT MIN(VSTB.D_VST_DATE) FROM DNR_VST_DB_REC VSTB WHERE VST.D_VST_INSTID = VSTB.D_VST_INSTID AND VSTB.D_VST_STATUS = 'DN' AND VST.D_VST_ID = VSTB.D_VST_ID) AND NOT EXISTS (SELECT R_DRC_ID FROM REC_DRC_DB_REC WHERE R_DRC_ID = COUNT_ID AND R_DRC_INSTID = COUNT_INSTID AND R_DRC_RESPCD = '15') GROUP BY NAM.N_NAM_ID, NAM.N_NAM_INSTID, NAM.N_NAM_FNAME, NAM.N_NAM_MINITIAL, NAM.N_NAM_LNAME, PER.N_PER_BIRTH, ADR.N_ADR_ADDR1, ADR.N_ADR_ADDR2, ADR.N_ADR_CITY, ADR.N_ADR_STATE, ADR.N_ADR_ZIP, PER.N_PER_EMAIL, PER.N_PER_GENDER, PHNA.N_PHN_AREACD, PHNA.N_PHN_PREFIX, PHNA.N_PHN_NUMBER, PHNA.N_PHN_EXTENTN, PHNB.N_PHN_AREACD, PHNB.N_PHN_PREFIX, PHNB.N_PHN_NUMBER, PHNB.N_PHN_EXTENTN, BTY.D_BTY_ABO, BTY.D_BTY_RHESUS, VST.D_VST_DATE, DV2.COUNT_VISITS, DTS.D_DTS_DONSUM, ELG.D_ELG_RWBDTE
Error Message:
(845 row(s) affected)
(844 row(s) affected)
(396 row(s) affected)
Server: Msg 9002, Level 17, State 6, Line 2 The log file for database 'tempdb' is full. Back up the transaction log for the database to free up some log space. Server: Msg 1105, Level 17, State 1, Line 2 Could not allocate space for object '(SYSTEM table id: -109901351)' in database 'TEMPDB' because the 'DEFAULT' filegroup is full.
I am not a SQL programmer, but I am trying to use data collected in our Job Costing system to feed data to a crystal report that summarizes the current department name and the last date each job was scanned into a department. I used aliases of the Process table to extract the max date for each department.
This statement works fine, but sometimes it hangs and locks my process table. I am not sure what event causes the lock, but I think it has to do with the users aborting the report during the SQL extract or multiple users trying to report at the same time (8am when they first arrive at work).
I showed this to a consultant and he showed me that the MAX statement in the 3rd to last join was eating most of the execution time. Also he told me I am using too many joins and should look into Table Views. The statement completes in 15 to 45 seconds, depending on the workload.
What can I do to improve the performance of this code and to avoid the locks?
SELECT OH.JobNumber, OH.PlantID, OH.CreateOpr, OC.ComponentNumber, PJN.ProductionCode as ProductionMax, P2.ProcessCode as MaxCC, PS.Description AS MaxCCDesc, PJ1.ProductionCode, P.ProcessCode as ProdCC, P51.CreateDatim AS SchCCDate, P53.CreateDatim AS TypCCDate, P55.CreateDatim AS OPrCCDate, P57.CreateDatim AS HPrCCDate, P59.CreateDatim AS CRmCCDate, P61.CreateDatim AS CCeCCDate, P63.CreateDatim AS PRmCCDate, P65.CreateDatim AS BinCCDate, P67.CreateDatim AS JbOCCDate, P69.CreateDatim AS OnDCCDate, P71.CreateDatim AS ShpCCDate, PS1.Description AS CCDesc, P.CreateDatim AS CCDate, OQT.Quantity, OH.JobDescription, OH.FormNumber, OH.JobDescription, OH.USERDEFINED1 AS JobType, OH.CustAccount, OH.CustName, (select OrderHeader.DueDate from OrderHeader where OrderHeader.JobNumber = OH.JobNumber and OH.NoDueDate = 0) as DueDate, OH.ProofDate, OH.OrderDate, OH.SalesRepCode, OH.PONumber, OH.PrevPONumber, OH.NoDueDate, OC.UserDefined1, OC.Description as ComponentDescription FROM OrderComponent OC INNER JOIN OrderHeader OH ON OC.JobNumber = OH.JobNumber INNER JOIN OrderQtyTable OQT ON OC.JobNumber = OQT.JobNumber and OC.ComponentNumber = OQT.ComponentNumber and OC.QtyOrdIndex = OQT.QuantityLineNo LEFT JOIN ProductionJobNumber PJ1 ON PJ1.JobNumber = OH.JobNumber and PJ1.ComponentNumber = OC.ComponentNumber LEFT JOIN Production P ON PJ1.ProductionCode = P.Code LEFT JOIN Production P51 ON PJ1.ProductionCode = P51.Code AND P51.ProcessCode = 9151 LEFT JOIN Production P53 ON PJ1.ProductionCode = P53.Code AND P53.ProcessCode = 9153 LEFT JOIN Production P55 ON PJ1.ProductionCode = P55.Code AND P55.ProcessCode = 9155 LEFT JOIN Production P57 ON PJ1.ProductionCode = P57.Code AND P57.ProcessCode = 9157 LEFT JOIN Production P59 ON PJ1.ProductionCode = P59.Code AND P59.ProcessCode = 9159 LEFT JOIN Production P61 ON PJ1.ProductionCode = P61.Code AND P61.ProcessCode = 9161 LEFT JOIN Production P63 ON PJ1.ProductionCode = P63.Code AND P63.ProcessCode = 9163 LEFT JOIN Production P65 ON PJ1.ProductionCode = P65.Code AND P65.ProcessCode = 9165 LEFT JOIN Production P67 ON PJ1.ProductionCode = P67.Code AND P67.ProcessCode = 9167 LEFT JOIN Production P69 ON PJ1.ProductionCode = P69.Code AND P69.ProcessCode = 9169 LEFT JOIN Production P71 ON PJ1.ProductionCode = P71.Code AND P71.ProcessCode = 9171 LEFT JOIN Process PS1 ON P.ProcessCode = PS1.ProcessCode LEFT JOIN ProductionJobNumber PJN ON PJN.ProductionCode = (select MAX(ProductionJobNumber.ProductionCode) From ProductionJobNumber where OH.Jobnumber = ProductionJobNumber.JobNumber AND OC.ComponentNumber = ProductionJobNumber.ComponentNumber) LEFT JOIN Production P2 ON PJN.ProductionCode = P2.Code LEFT JOIN Process PS ON P2.ProcessCode = PS.ProcessCode WHERE OH.JobStatus = 'IN PROCESS'
What i want to happen is Table_A will hold a recid and an update field. within the if statement it needs to JOIN with Table_B ON recid and check the value of one/two possible fields to determine if that recid goes to Table_F or Table_G
I need to get this INNER JOIN embedded in a nested if along with more INNER JOINs
INSERT BACKFILE_AP SELECT WORK_INTRO.RECID, WORK_INTRO.UPDATED FROM WORK_INTRO INNER JOIN SIF_DT1 ON WORK_INTRO.RECID = SIF_DT1.RECID WHERE SIF_DT1.ROUTE_CODE = 'BACKFILE' DELETE WORK_INTRO FROM WORK_INTRO INNER JOIN SIF_DT1 ON WORK_INTRO.RECID = SIF_DT1.RECID WHERE SIF_DT1.ROUTE_CODE = 'BACKFILE'
Heya - Very new here to SQL, but when I do this following query
SELECT ProjMgr, SUM(Fee) AS Fee FROM dbo.PR WHERE (ProjMgr = '00138') GROUP BY ProjMgr
I return these results:
ProjMgrFee 001389145297
Simple enough, so I flex my newbie SQL muscles and put in the last name instead of the ProjectManager's employee number
SELECT dbo.EM.LastName, SUM(dbo.PR.Fee) AS Fee FROM dbo.PR INNER JOIN dbo.EM ON dbo.PR.ProjMgr = dbo.EM.Employee WHERE (dbo.PR.ProjMgr = '00138') GROUP BY dbo.EM.LastName
And get these results
LastNameFee Boulet9145297
Okay, NOW I'm getting cocky. I try to bring in an amount indicating held labor from another table that will have multiple instances of the same number, called WBS1, and show a sum of values contained over months of history in a sum. Before I do that, I add the table, and then I'm stuck - look what happens to my fee column...any ideas?
SELECT dbo.EM.LastName, SUM(dbo.PR.Fee) AS Fee FROM dbo.PR INNER JOIN dbo.EM ON dbo.PR.ProjMgr = dbo.EM.Employee INNER JOIN dbo.LD ON dbo.PR.WBS1 = dbo.LD.WBS1 WHERE (dbo.PR.ProjMgr = '00138') GROUP BY dbo.EM.LastName