Delete Query Using Join

Jun 5, 2007

I need to delete records from one table base on criteria from another table. The example below from the Northwind database shows exactly what I want to do. I want to delete the records from the employee table who a terrorityID of 30346 in the EmployeeTerritories table.

Can someone tell me how to write a delete statement that will delete the rows returned from the following SQL Statement? The sql statement will return one employee name. I would lke to delete that one employee from the employee table and I haven’t been able to figure out how to do it.

////////// Sql Statment
SELECT dbo.EmployeeTerritories.EmployeeID, dbo.EmployeeTerritories.TerritoryID
FROM dbo.EmployeeTerritories INNER JOIN
dbo.Employees ON dbo.EmployeeTerritories.EmployeeID = dbo.Employees.EmployeeID
WHERE (dbo.EmployeeTerritories.TerritoryID = N'30346')
////////// end of sql statement

Thanks
GEM

View 3 Replies


ADVERTISEMENT

Delete Query With Inner Join

Nov 21, 2005

Hallo,

Can anybody let me know what I need to change to make this query work:

delete
from a
inner b
on a.item = b.item

I get the error message "Incorrect syntax near the keyword 'inner'."

Thanks,
Stephen.

View 3 Replies View Related

DELETE Query - Can't JOIN. Need Sub-query?..

Mar 30, 2007

I need to run a DELETE query based on 2 tables. I can't use JOIN with delete queries, so how do I do this?

What I initially tried to do was:

Code:

DELETE FROM tblProductState
JOIN tblProduct
ON tblProduct.id_Product = tblProductState.id_Product
WHERE tblProductState.id_State = 54 AND tblProduct.id_ProductType = 1


Basically, I need to delete FROM tblProductState, WHERE tblProductState.id_State = 54 AND tblProduct.id_ProductType = 1

How can I do this without using JOIN. Use a sub-query? How?

Thanks

View 4 Replies View Related

SQL Delete With Join

Nov 24, 1998

I am getting SEVERE performance problems with the following delete...

delete namelist where str(na_id) + str(na_liid) in (select str(na_id) + str(na_liid) from tnamelist)

... where na_id and na_liid are INT character types.

The individual fields are both indexed on both tables.

I can see no other factors affecting this query.

Any ideas as to how I can optimize this better?

Bob

View 1 Replies View Related

Delete With Join

Sep 27, 2005

-- Idea behind writing this query is to remove duplicate record

t1 table structure as follow
<sno> <identity> int
<value> <char(100)>

t1_tmp is just a replica of t1 with same values


Let say t1 has following value

1Amit
2Amit
3Amit
4Amit
5k
6k
7k



result must be

1 Amit
5 K


BUt when I run below query, it delete all rows... please help, I am newbia

delete from t1
from t1_tmp
where t1.sno <> t1_tmp.sno
and t1.value = t1_tmp.value



As

View 4 Replies View Related

Delete With Inner Join

Dec 12, 2007

below is my procedure i m deleting records with inner join

CREATE PROCEDURE sp_DeleteSkill
(
@SkillID integer,
-- Start 12/12/2007 Shailesh dubey DeVtask 07180
@ClientID integer,
@IsGlobal bit ,
@ParentModuleID int,
@ClientAccessID int,
@GroupID int
-- End 12/12/2007 Shailesh dubey DeVtask 07180
)
AS
BEGIN
DELETE FROM t_ClientSkills INNER JOIN dbo.fn_GetMyEmployeesByAreaAccess(@IsGlobal, @ParentModuleID, @ClientAccessID, @GroupID, 0, '', '', '') AS EMP ON (t_ClientSkills.ClientID = EMP.ClientID) WHERE SkillID = @SkillID AND ClientID = @ClientID

IF @@ERROR <> 0
BEGIN
RETURN(0) --Failed
END
ELSE
BEGIN
RETURN(1) --Success
END
END

getting below error

Server: Msg 156, Level 15, State 1, Procedure sp_DeleteSkill, Line 40
Incorrect syntax near the keyword 'INNER'.

what i m missing?

View 4 Replies View Related

Delete Statement Using A Join Plz Help

Mar 2, 2005

well i have 2 table one name detcom and another entcom stored in DB1 the key for both to join on is lets say A, B, C . I need to check if there are records based on the key A, B, C of both table where C EQUALS to '80_300_113' and if there are delete them and then grab data from another
database named DB2 on same server (same instance) wich contains the same tables entcom and detcom and insert all the data from those tables into the same tables in DB1 based on the key and where C = '80_300_113'

PLZ help

View 1 Replies View Related

Delete With Left Join

Feb 20, 2015

What is the logic of the below DELETE statement?It deletes all records where the file_modified column value is smaller then the maximum value in the same column, but not crystal clear how...

delete a
from Staging a
left join (select max(file_modifieddate) as file_modifieddate from Staging) b on
a.file_modifieddate = b.file_modifieddate
where b.file_modifieddate is null

View 2 Replies View Related

I Use SQL 2000, Can You Use One Delete Query To Delete 2 Tables?

Nov 26, 2007

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

View 1 Replies View Related

How To Run Delete Query / Delete Several Rows Just By One Click ?

Feb 16, 2008

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) 

View 2 Replies View Related

Multiple Record Delete Via Join

Feb 25, 2008

Hi,

I have a table with a large number of records that I need to delete, before attempt to perform the delete I also archived the records to another table.

So I need to delete all of these selected records stored in the archive table from the main table. I can now reference all the records that qualify for the delete in the main table by performing a join on the archive table like so:

select * from my_main_table a
join my_archive_table b
on a.distinct_id=b.distinct_id
and a.surrogate_key=b.surrogate_key
and a.identifier=b.indentifier

So all the records check out to be the ones I'd like to perform a delete on but I just can't figure out how to perform a delete of the records with little or no change to the existing query.

Obviously something like this won't work:

delete from my_main_table a
join my_archive_table b
on a.distinct_id=b.distinct_id
and a.surrogate_key=b.surrogate_key
and a.identifier=b.indentifier

Though it would be nice if it did.:D

So my question is how would I use the existing query with some modification to delete only the records that this query returns. I've tried selection of records in the main table based on the existing records in the archive table but it can return a higher number of records than what I know is expected. I actually need the join specified to be in place to do it.

Can anyone render any assistance on this one???

I would certainly appreciate it.

Thanks.

View 1 Replies View Related

Combining DELETE And JOIN Statements

Nov 20, 2006

In SQL Server 2000/2005 (not CE) I can use the following T-SQL statement to delete orphaned rows from a table:

DELETE GroupsMembers FROM GroupsMembers LEFT OUTER JOIN Groups ON GroupsMembers.GroupID = Groups.ID WHERE Groups.ID IS NULL

SQL Server CE does not seem to support combining the JOIN statement with the DELETE statement. Is this correct? If yes, is there any alternative statement that could be used to accomplish the same thing?

Gerrit

View 3 Replies View Related

Multi-table JOIN Query With More Than One JOIN Statement

Apr 14, 2015

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.

View 2 Replies View Related

Why Does My Query Timeout Unless Force Join To Hash Join?

Jul 25, 2007

I'm using SQL Server 2005.



A piece of software I wrote starting timing out on a query that left outer joins a table to a view. Both the table and view have approximately the same number of rows (about 170000).



The table has 2 very similar columns, one is a varchar(1) and another is varchar(100). Neither are included in any index and beyond the size difference, the columns have the same properties. One of the employees here uses the varchar(1) column (called miscsearch) to tag large sets of rows to perform some action on. In this case, he had set 9000 rows miscsearch value to "g". The query then should join the table and view for all rows where miscsearch is set to g in the table. This query takes at least 20 minutes to run (I stopped it at this point).

If I remove the "where" clause and join all rows in the two tables, the query completes in about 20 seconds. If set the varchar(100) column (called descrip) to "g" for the same rows set via miscsearch, the query completes in about 20 seconds.



If I force the join type to a hash join, the query completes using miscsearch in about 30 seconds.



So, this works:

SELECT di.File_No, prevPlacements, balance,'NOT PLACED' as status FROM Info di LEFT OUTER HASH JOIN View_PP pp ON di.ram_file_no = pp.file_no WHERE miscsearch = 'g' ORDER BY balance DESC



and this works:

SELECT di.File_No, prevPlacements, balance,'NOT PLACED' as status FROM Info di LEFT OUTER JOIN View_PP pp ON di.ram_file_no = pp.file_no WHERE descrip = 'g' ORDER BY balance DESC



But this does't:

SELECT di.File_No, prevPlacements, balance,'NOT PLACED' as status FROM Info di LEFT OUTER JOIN View_PP pp ON di.ram_file_no = pp.file_no WHERE miscsearch = 'g' ORDER BY balance DESC



What should I be looking for here to understand why this is happening?



Thanks,

john















View 1 Replies View Related

SQL Query Question - JOIN Or Not To JOIN

Jan 2, 2006

I have 2 tables, I will add sample data to them to help me explain...Table1(Fields: A, B)=====1,One2,Two3,ThreeTable2(Fields: A,B)=====2,deux9,neufI want to create a query that will only return data so long as the key(Field A) is on both tables, if not, return nothing. How can I dothis? I am thnking about using a 'JOIN' but not sure how to implementit...i.e: 2 would return data- but 9 would not...any help would be appreciated.

View 3 Replies View Related

Can Any One Tell Me The Difference Between Cross Join, Inner Join And Outer Join In Laymans Language

Apr 30, 2008

Hello

Can any one tell me the difference between Cross Join, inner join and outer join in laymans language

by just taking examples of two tables such as Customers and Customer Addresses


Thank You

View 1 Replies View Related

Delete Query

Feb 28, 2008

Hi
I need some help on a query. I need to delete some records from a table, this table has a dependency to another table
Table 1: dbo.Accounts and Table 2: dbo.AccountsToUser
In the dbo.Accounts table there are
AccountId and OwnedByAccountId
54708002 54708001 54708003 54708001 65708002 65708001 65708003 65708001 54708001 2233440165708001 NULL
In the dbo.AccountsToUser there are
AccountId and UserId
65708002 10065708003 10165708003 10465708003 10654708001 19465708002 199
What I need is to delete every record from dbo.AccountsToUser that has an account connection to an account in the dbo.Accounts that has OwnedByAccount like NULL
So in the example above I should delete from dbo.AccountsToUser
65708002 10065708003 10165708003 10465708003 106
Since they are connected to 65708001 which has OwnedByAccountStatus like NULL
I could delete the records manually since the table is still hand able, but I need this to be a daily job so all help would be very nice
Thanks!
 

View 6 Replies View Related

Delete Query

Mar 31, 2008

Can any one please correct this query.Shall i write like this.Please correct this query.
 Delete globalDocs.dbo.gdoc_File set IsTrue=1 where FileID='abc'

View 6 Replies View Related

Is There Any Sql Query To Delete Any Particular Row

Apr 11, 2008

In sql server ...is there any opton to delete any particular row..
i have table student
no name
1    raja
2    pravin
3   abraham
 
suppose i what to delete 2nd row is there any option to delete whithout specifying no or name just only row(ie 2)
pl reply me....

View 6 Replies View Related

Delete Query?

Apr 12, 2008

Hi friends, I want to delete more than record using id.i pass group of id(with string concat) like 10|11|20|25. in stored procedure i want to delete corresponding record.10112025 any idea?Thanks,Durai 

View 3 Replies View Related

Delete Query

Feb 25, 2002

Below are 2 tables and data that I have.

Table1

col1col2col3
--------------------
11aaa
12bbb
13ccc
21ppp
22qqq
23rrr

Table2

col1col2
-------------
11
12
21

Now I want to delete all rows from Table1 which doesn't have a matching entry in Table 2. After the delete, this is what my Table1 data should be:

Table1

col1col2col3
--------------------
11aaa
12bbb
21ppp

Can some one give me a query to accomplish this? Thanks in advance for your help.

View 1 Replies View Related

Delete Query Help

Oct 7, 2006

Hi folks

Hoping someone can help me out with my query query!

I'm trying to write a script to do the following: delete everything from table1 where column A and B (of table1) does not match column A and B of table2

Any ideas??

Thanks as ever,
Georgia

View 1 Replies View Related

Delete Query ?

Aug 2, 2004

Hi,

Is this a valid SQL Server query :

DELETE FROM D FROM D WHERE LEFT JOIN H ON H.key=D:key WHERE H.key IS NULL

Please advise.

Thanks,
Sam

View 1 Replies View Related

Delete Query ?

Aug 2, 2004

Hi,

Is this a valid SQL Server query :

DELETE FROM D FROM D WHERE LEFT JOIN H ON H.key=D.key WHERE H.key IS NULL

Please advise.

Thanks,
Sam

View 2 Replies View Related

Help With Delete Query

Apr 5, 2007

Hi,

Not sure if this is possible in a delete query that is why I'm posting out of curiosity.

I have a table with one column (int datatype)

WorkItem
1
1
2
1
3
1

----(6 rows)

Can I delete the first record whose workitemid is 1

So that after the delete the resulting dataset in

WorkItemID
1
2
1
3
1

----(5 rows)

Thanks,

yumyum113

View 8 Replies View Related

Delete Query

May 25, 2007

hi all,
how do i perform this query?

DELETE FROM tblStkAdjDetail
WHERE (SELECT ItemStorageID FROM tblStkAdjDetail WHERE Status='NEW'
AND ItemStorageID NOT IN (SELECT ItemStorageId FROM tblTempTableForRecvPacking) )


~~~Focus on problem, not solution ¯(º_o)/¯ ~~~

View 10 Replies View Related

Query Regarding Delete

Feb 21, 2008

Hi All

I am beginner ot SQL Server.
I want to know that when we delete a row or a set of Rows from a table, it'll only make the space available for subsequent inserts into it or will the Delete also free the memory used by the table.

Suppose I am inserting customer records in the details table when the customer comes into the system. If i make a logic to delete the customer record from the table and insert into the backup table when it leaves the system(As the data inserted is quite large and my application queries into this table at each transaction). Will it help in optimizing the SQL Queries or it is useless to do so.

Thanks
Harsh Dhawan


Harsh Dhawan

View 4 Replies View Related

Delete Query

Aug 7, 2007

I have part of a stored proc that I need help with.
I need to figure out how to delete infro from the
tblManifest using the @ssnDelete variable.
I Have multiple records ffor the given above variable.

Would this need to loop in order to work and that is the solution for this.

I get ther following error when I run the full stored proc.
------------------------------

Msg 512, Level 16, State 1, Line 2

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
------------------------------


Here is the code fro part of the proceedure.
Thanks in advance.

Gene
----------------------------------------------------------

CREATE TABLE dbo.tblTempSSN(

ssn varchar(11) null);


OPEN SYMMETRIC KEY SymKeySSN

DECRYPTION BY CERTIFICATE CertSSN;

INSERT INTO tblTempSSN(ssn)

SELECT CONVERT(VARCHAR(11), DecryptByKey(s.SSN)) AS SSN

FROM tblSoldier s, tblManifest m

WHERE CONVERT(VARCHAR(11), DecryptByKey(s.SSN)) = m.ssn

CLOSE SYMMETRIC KEY SymKeySSN;


declare @ssnDelete varchar(11);

set @ssnDelete = (select (m.ssn) as ssn

from tblManifest m, tblTempSSN t

where t.ssn = m.ssn);


delete

from tblManifest

where ssn = '@ssnDelete';



DROP TABLE dbo.tblTempSSN;
----------------------------------------------------------

View 2 Replies View Related

Delete Query

Aug 7, 2007

I have part of a stored proc that I need help with.
I need to figure out how to delete infro from the
tblManifest using the @ssnDelete variable.
I Have multiple records ffor the given above variable.

Would this need to loop in order to work and that is the solution for this.

I get ther following error when I run the full stored proc.
------------------------------

Msg 512, Level 16, State 1, Line 2

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
------------------------------


Here is the code fro part of the proceedure.
Thanks in advance.

Gene
----------------------------------------------------------

CREATE TABLE dbo.tblTempSSN(

ssn varchar(11) null);


OPEN SYMMETRIC KEY SymKeySSN

DECRYPTION BY CERTIFICATE CertSSN;

INSERT INTO tblTempSSN(ssn)

SELECT CONVERT(VARCHAR(11), DecryptByKey(s.SSN)) AS SSN

FROM tblSoldier s, tblManifest m

WHERE CONVERT(VARCHAR(11), DecryptByKey(s.SSN)) = m.ssn

CLOSE SYMMETRIC KEY SymKeySSN;


declare @ssnDelete varchar(11);

set @ssnDelete = (select (m.ssn) as ssn

from tblManifest m, tblTempSSN t

where t.ssn = m.ssn);


delete

from tblManifest

where ssn = '@ssnDelete';



DROP TABLE dbo.tblTempSSN;
----------------------------------------------------------

View 4 Replies View Related

SQL Query - Delete All Rows Bar The Last 10? Help Please!

Jan 6, 2008

Hi,
I'm really not very good at SQL sadly, so would really appreciate any help.
I'm basically working on a website that has a chatroom. I want it so the chatroom table only holds, say 15 lines of chat, then once a new line of chat is entered the last line in the table is deleted, so the table always has a maximum of just 15 rows.
The fields are:
MessageID
Poster
Message
DateTime
I've tried my best, but just don't know how to do it.
I suppose it's something like:
SELECT TOP 15 * FROM Chatroom ORDER BY MessageID DESC - this gives me the last 15 rows.
Then I need a delete statement to delete the rest?! Sorry, I am very bad at SQL, so any help would be great. This is written in a stored procedure.
Can the stored procedure pick up whether there are 15 or more rows in the table, and if so then delete all bar the newest 15 rows of chat?
To summarise: I want a stored procedure that checks if 15 or more rows exist, if they do then delete all bar the newest 15 rows.
Thanks,
Ricky

View 5 Replies View Related

Unusual Delete Query

Oct 3, 2000

We're trying to construct a query that deletes records containing 48 particular phone numbers from a large db. The 48 numbers are the entire contents of a smaller db, in a field of the same name as in the larger db (home_phone). We're using Sequel Server 7.0 and Access 97. The db's are in Access now. We failed in Acess and now would like to import into sql and try it there.
Thanks,
Tad McArdle

View 1 Replies View Related

Delete From 2 Tables With 1 SQL Query

Mar 23, 2004

I have 2 tables that are joined together by a primary key (Order Number). Can I use one SQL query to delete from both of the tables. One table contains the order information from a client (Order Number, Customer Name etc). The other table has order information (Order Number, Item Number, Quantity Ordered etc.)

I need one statement that will allow me to remove the items from both tables. Can this be done.

Thanks in Advance

Wes

View 6 Replies View Related

Error In Delete Query

Apr 7, 2004

What is the problem in :


DELETE FROM tblPickingTask
LEFT OUTER JOIN tblPickingSlip ON tblPickingTask.SPSID = tblPickingSlip.SPSID
WHERE tblPickingSlip.SPSID IS NULL


I whan to delete all record in tblPickingTask was not in tblPickingSlip

View 3 Replies View Related







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