Showing posts with label key. Show all posts
Showing posts with label key. Show all posts

Thursday, March 29, 2012

deleting records in associated foeign key table

Hi, i need the suggestion here in very familiar db situation ..i have a main table and a primary key of that table is used in many other table as foreign key.If i am deleting a record in a main table,how do i make sure that all the corresponding record in the associated tables,where that foreign key is used, gets deleted too?What are my options?Thanks

There are a few options, but the best two, IMO, are:

Write a SQL statement that first deletes the associated records and then deletes the parent record. Imagine that you had a Categories table and a Products table, and there is a one to many relationship from Categories to Products. Now, imagine that we wanted to delete a category that has associated products. We'd first need to delete the Products - DELETE FROM Products WHERE CategoryID = @.CategoryIDToDelete - then we'd delete the category: DELETE FROM Categories WHERE CategoryID = @.CategoryIDToDelete.
|||

Thank a lot Scott for quick response...i have got multiple tables and all these table are kind of chained up with each other using multiple foreign key .i am liking the idea of 'cascade delete',I have already set up the foreign key constraints in all these table.I will read up on cascade delete,,have no idea about it rightnow...

|||

Scott is correct on the two main options. Given that this question is a "newbie" question, it's probably best to clarify that the first option is to write TWO sql statements, not one - a delete for each table.

|||

David, do you mean,two sql statements(or as many delete as reqd for linked up tables) within one stored procedures or two(or multiple depends?) separate sql statements ?i am heavily using SP in my application.thanks

|||

I mean 1 delete statement per table that needs deleting. Those delete statements can be in one stored procedure.

My comments were to avoid some one new to sql trying to issue a delete statement like this (because it will never work):

delete department and employee where department_id = 5

Tuesday, March 27, 2012

Deleting primary key when no foreign records exist?

Is there a trigger that would handle this situation? I have a 1 to
many between two tables and would like the primary key deleted if the
last foreign record is deleted.
Thanks in advance!Sure, in an AFTER trigger on the child table, something like (including a
scenario to try it out.):
set nocount on
go
create table parent
(
parentKey int primary key
)
create table child
(
childKey int primary key,
parentKey int foreign key references parent(parentKey)
)
insert into parent
select 1
union all
select 2
union all
select 3
insert into child
select 1,1
union all
select 2,1
union all
select 3,1
union all
select 4,2
union all
select 5,2
union all
select 6,2
union all
select 7,3
union all
select 8,3
go
create trigger child$deleteTrigger
on child
after delete
as
--be sure to add error handling
delete parent
--this gets all parent rows that are related to the deleted child rows based
on the migrated key from the parent
where exists (select 1
from deleted
where parent.parentKey = deleted.parentKey)
--this excludes parents where a child still exists
and not exists (select 1
from child
join deleted
on child.parentKey =
deleted.parentKey
where parent.parentKey = deleted.parentKey)
go
delete child where parentkey = 1
select *
from parent
left outer join child
on parent.parentKey = child.parentKey
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"CJ" <Charles.Deisler@.gmail.com> wrote in message
news:1139625347.478136.146410@.g14g2000cwa.googlegroups.com...
> Is there a trigger that would handle this situation? I have a 1 to
> many between two tables and would like the primary key deleted if the
> last foreign record is deleted.
> Thanks in advance!
>|||Many thanks Louis!|||Yes, you can do this with a trigger, if you like to write procedural,
proprietary code. Look for a COUNT(*) = 0 in a PK-FK join.
Another way to do this is to put one "child" item the same table as the
"parent" since you seem to require at least one "child" as part of the
design. When you delete the "only child", you have to delete the
parent.
Oh, did I mention that the code is messy?|||> Another way to do this is to put one "child" item the same table as the "p
arent"
Joe,
Are you saying your solution conforms to 3NF?
What if later you'll need to delete the child row stored along with the
parent? You'll have to move another row from the child table to the
parent one. Are you claiming it's less messy than Louis's solution?
Also instead of selects against the child table you'll have to select
against a union of the child and the parent, right?
How would you enforse a unique constraint on the child?sql

Sunday, March 25, 2012

Deleting min value from grouped records

I have a table where no keys are currently defined, so we have dups...kind
of. In this table the account number with be the primary key, and we also
have a date field. There are records in there that have the same account
number, but a different date. I want to find the duplicates, which is the
easy part. Then from there I want to delete the record that has the oldest
date. Example
record 1
account 1
date 1-1-2004
record 2
account 1
date 5-1-2004
I want to delete record 1. I am having trouble coming up with the code.
Any help is appreciated.
ThanksTry,
delete t1
where exists(select * from t1 as a where a.account_id = t1.account_id and
a.col_date > t1.col_date)
This will not eliminate duplicated rows with same col_date.
AMB
"Andy" wrote:

> I have a table where no keys are currently defined, so we have dups...kin
d
> of. In this table the account number with be the primary key, and we also
> have a date field. There are records in there that have the same account
> number, but a different date. I want to find the duplicates, which is the
> easy part. Then from there I want to delete the record that has the oldes
t
> date. Example
> record 1
> account 1
> date 1-1-2004
> record 2
> account 1
> date 5-1-2004
> I want to delete record 1. I am having trouble coming up with the code.
> Any help is appreciated.
> Thanks|||Delete SomeTable
from SomeTable
INNER JOIN
(
Select MIN([Date]), account from SomeTable
Group by account
) Subquery
on
Subquery.record = SomeTable.Record AND
Subquery.account = SomeTable.account AND
Subquery.[date] = SomeTable.[date]
HTH, Jens SUessmeyer.
"Andy" <Andy@.discussions.microsoft.com> schrieb im Newsbeitrag
news:4F5EBDA6-6BAE-44D0-9413-869F150B3640@.microsoft.com...
>I have a table where no keys are currently defined, so we have dups...kind
> of. In this table the account number with be the primary key, and we also
> have a date field. There are records in there that have the same account
> number, but a different date. I want to find the duplicates, which is the
> easy part. Then from there I want to delete the record that has the
> oldest
> date. Example
> record 1
> account 1
> date 1-1-2004
> record 2
> account 1
> date 5-1-2004
> I want to delete record 1. I am having trouble coming up with the code.
> Any help is appreciated.
> Thanks|||Are you sure you "want to delete the record with the oldest Date" and that's
all? W
--What if there is only one record?
-- What if there are morethan 2 records?
Most of the time what is desired is t odelete ALL BUT The most recent
record... whichis actually easier..
But...
Delete T
From Table T
Where DateCol =
(Select Min(DateCol) From Table
Where AccountNo = T.AccountNo)
-- Add this if you only want to delete when there are dupes with same
accountNo
And Exists (Select * From Table
Where AcountNo = T.AccountNo
And DateCol > T.DateCol)
This will delete all reco
"Andy" wrote:

> I have a table where no keys are currently defined, so we have dups...kin
d
> of. In this table the account number with be the primary key, and we also
> have a date field. There are records in there that have the same account
> number, but a different date. I want to find the duplicates, which is the
> easy part. Then from there I want to delete the record that has the oldes
t
> date. Example
> record 1
> account 1
> date 1-1-2004
> record 2
> account 1
> date 5-1-2004
> I want to delete record 1. I am having trouble coming up with the code.
> Any help is appreciated.
> Thanks

Deleting foreign key record

Hi all,.

I have a table Student and the primarykey is studid..

This studid is the foreign key in another table called Class.

I want to delete the records in the table Class...

How can i do it..

Please help me...

Regards,

Mathewyou'll need to drop the foreign keys between the two tables delete the required data, and add the foriegn keys once again.|||

Quote:

Originally Posted by jamesd0142

you'll need to drop the foreign keys between the two tables delete the required data, and add the foriegn keys once again.


Hi James,

Is that the only method to delete those records??

Regards,
Mathew|||What error are you getting when you try to delete these records?

this will help me determine if i have suggested the correct method...

because you shouldnt really get any issues deleting a row frm the table 'class'

i can see y u wud get an error deleting a record from Student table however.|||

Quote:

Originally Posted by jamesd0142

What error are you getting when you try to delete these records?

this will help me determine if i have suggested the correct method...

because you shouldnt really get any issues deleting a row frm the table 'class'

i can see y u wud get an error deleting a record from Student table however.


Hi all,

I didnt try to delete record.. i have to do it,, before that i would like to know whether it is possible or not....

regards,
Mathew|||

Quote:

Originally Posted by mathewgk80

Hi all,

I didnt try to delete record.. i have to do it,, before that i would like to know whether it is possible or not....

regards,
Mathew


Ok, well as i said above, i can's see any problems with deleting from the 'class' table, although you might have a problem deletiung from the 'student' table because;

The studid field in the 'class' table would no longer have a lookup, so droping the foriegn keys first would allow you to delete a record in 'student', although if you have a value in the 'class' table for studid thats not in the 'student' table you 'shouldnt' be able to create the foriegn keys once again...

i hope you understand my logic here :ssql

Thursday, March 22, 2012

Deleting duplicate rows from a table, having no primary key

I am looking at various methods to delete records from a table which has duplicate records and does not have a foriegn key, in a single query.
One of the methods is using the rowid.
Looking for more.
VisheetalThat would be the easiest.sql

Deleting duplicate entries in nightmare-table

Hello
I was given the task to "filter away" duplicate rows in a 10 million row
table with about 30 columns :S And the table has no primary key, no
constrains, nothing, and I need to find a way to clear that mess up, in a
way... sigh
You guys must think, alright, this is easy, just group by, well well, that
would be too easy, since each row isnt really "unique", lets continue the
mess....
Lets say the table contains 5 columns, A B C D E
In the new table there shall be a CHECK(A,B,C), that combination is unique.
But in the old table there are duplicates of that, and the values of D and E
may be any value on each row. (Headache yet?) Ppl who create these kinds of
heaptables should be lined up and shot :(
Lemme post some test DLL:
CREATE TABLE #Test (
A int,
B int,
C int,
D int,
E int
)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,9,8)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,-1,6)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,2,1,1,4)
INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,1,4)
INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
SELECT * FROM #Test
/*
DESIRED RESULT
A B C D E
1,1,1,9,8
1,2,1,1,4
3,2,1,1,4
*/
DROP TABLE #Test
And everything is so screwed up it doesnt "matter" which values D and E has
(or the other 20 columns) as long as they had the value it had before. And
all columns are like varchar(x) in the table, so keep that in mind :S> And everything is so screwed up it doesnt "matter" which values D and E
> has
> (or the other 20 columns) as long as they had the value it had before.
This doesn't make sense to me, which value did it have before?
Anyway, I'll try, can you do this:
SELECT A,B,C,MAX(D),MAX(E)
FROM table
GROUP BY A,B,C;
?
There is no ANY() function, so you either need to choose an aggregate, or
maybe you could use a correlated subquery with ORDER BY CHECKSUM(NEWID())
but I'm not clear that would work, nor without better requirements am I
inclined to try.
A|||Lasse Edsvik wrote:
> Hello
> I was given the task to "filter away" duplicate rows in a 10 million row
> table with about 30 columns :S And the table has no primary key, no
> constrains, nothing, and I need to find a way to clear that mess up, in a
> way... sigh
> You guys must think, alright, this is easy, just group by, well well, that
> would be too easy, since each row isnt really "unique", lets continue the
> mess....
> Lets say the table contains 5 columns, A B C D E
> In the new table there shall be a CHECK(A,B,C), that combination is unique
.
> But in the old table there are duplicates of that, and the values of D and
E
> may be any value on each row. (Headache yet?) Ppl who create these kinds o
f
> heaptables should be lined up and shot :(
> Lemme post some test DLL:
>
> CREATE TABLE #Test (
> A int,
> B int,
> C int,
> D int,
> E int
> )
> INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,9,8)
> INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,-1,6)
> INSERT INTO #Test(A,B,C,D,E)VALUES(1,2,1,1,4)
> INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,1,4)
> INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
> INSERT INTO #Test(A,B,C,D,E)VALUES(3,2,1,3,4)
>
> SELECT * FROM #Test
> /*
> DESIRED RESULT
>
> A B C D E
> 1,1,1,9,8
> 1,2,1,1,4
> 3,2,1,1,4
> */
> DROP TABLE #Test
>
> And everything is so screwed up it doesnt "matter" which values D and E ha
s
> (or the other 20 columns) as long as they had the value it had before. And
> all columns are like varchar(x) in the table, so keep that in mind :S
Always tell us what version of SQL Server you are using.
In SQL Server 2005:
WITH T (row_num) AS
(SELECT ROW_NUMBER() OVER
(PARTITION BY a,b,c ORDER BY a,b,c,d,e)
FROM #Test)
DELETE FROM T
WHERE row_num > 1;
Google for "delete duplicates" and you'll find lots of other solutions
in the archives of this group.
Test it out and make sure you have a current backup first :-)
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||David,
sry, forgot that :) I'm using SQL 2000
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1147360308.771189.249980@.i40g2000cwc.googlegroups.com...
> Lasse Edsvik wrote:
a
that
the
unique.
and E
of
has
And
> Always tell us what version of SQL Server you are using.
> In SQL Server 2005:
> WITH T (row_num) AS
> (SELECT ROW_NUMBER() OVER
> (PARTITION BY a,b,c ORDER BY a,b,c,d,e)
> FROM #Test)
> DELETE FROM T
> WHERE row_num > 1;
> Google for "delete duplicates" and you'll find lots of other solutions
> in the archives of this group.
> Test it out and make sure you have a current backup first :-)
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||Hi Aaron,
consider raw data like this:
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,9,6)
INSERT INTO #Test(A,B,C,D,E)VALUES(1,1,1,-1,8)
then the query
SELECT A,B,C,MAX(D),MAX(E)
FROM table
GROUP BY A,B,C;
will produce a row
1,1,1,9,8
which is not present in the original data. Does it make sence?|||alter table #test add f timestamp
go
select * from #test
go
select A,B,C,D,E from #test where not exists(select 1 from #test t1
where t1.a=#test.a
and t1.b=#test.b
and t1.c=#test.c
and t1.f>#test.f)
A B C D E
-- -- -- -- --
1 1 1 -1 6
1 2 1 1 4
3 2 1 3 4
(3 row(s) affected)|||> which is not present in the original data. Does it make sence?
I don't know, I don't think the requirements were specific enough to make
you right or to make me wrong. I was just offering one possible solution.

Deleting Duplicate Data


Hi to All!
I have a table with 60 columns and more than one million rows. i have to
implement composite primary key but it gives me error of duplicate data.
i have used following query to detect the duplicate rows
select NID,output_No from tbl_Data
group by NID,output_No
having count(*) > 1
it gives me 2526 duplicate dows. Now i wants to delete the duplicate
rows what will be the query for deleting the duplicate records.
Thanx
*** Sent via Developersdex http://www.examnotes.net ***This script has written by Itzik Ben-Gan
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"Ghulam Farid" <gfaryd@.yahoo.com> wrote in message
news:umVO5durFHA.3444@.TK2MSFTNGP12.phx.gbl...
>
> Hi to All!
> I have a table with 60 columns and more than one million rows. i have to
> implement composite primary key but it gives me error of duplicate data.
> i have used following query to detect the duplicate rows
> select NID,output_No from tbl_Data
> group by NID,output_No
> having count(*) > 1
> it gives me 2526 duplicate dows. Now i wants to delete the duplicate
> rows what will be the query for deleting the duplicate records.
>
> Thanx
>
> *** Sent via Developersdex http://www.examnotes.net ***|||Try this:
(1) SELECT columnList INTO workTable FROM tableName GROUP BY keyColumns
HAVING COUNT(*) > 1
(2) DELETE tableName FROM workTable WHERE tableName.keyColumns =
workTable.keyColumns
(3) INSERT tableName (columnList) SELECT columnList FROM workTable
(4) DROP workTable
You might want to wrap this in a transaction, but if you don't then a temp
table for the work table is contraindicated because if power goes out
between steps 2 and 3, you will lose the duplicate rows altogether.
If the table were tiny, you could use something like:
SET ROWCOUNT 1
AGAIN:
DELETE tableName FROM (SELECT keyColumns FROM tableName GROUP BY keyColumns
HAVING COUNT(*) > 1) a WHERE tableName.keyColumns = a.keyColumns
IF @.@.ROWCOUNT > 0 GOTO AGAIN
SET ROWCOUNT 0
"Ghulam Farid" <gfaryd@.yahoo.com> wrote in message
news:umVO5durFHA.3444@.TK2MSFTNGP12.phx.gbl...
>
> Hi to All!
> I have a table with 60 columns and more than one million rows. i have to
> implement composite primary key but it gives me error of duplicate data.
> i have used following query to detect the duplicate rows
> select NID,output_No from tbl_Data
> group by NID,output_No
> having count(*) > 1
> it gives me 2526 duplicate dows. Now i wants to delete the duplicate
> rows what will be the query for deleting the duplicate records.
>
> Thanx
>
> *** Sent via Developersdex http://www.examnotes.net ***

Wednesday, March 21, 2012

Deleting all without contraints

I have a table that has about 10 different foreign key and trigger
contraints. I am wanting to setup a delete that will delete records
that do not have a contraint problem.
The problem is that once it hits one record with a contraint problem it
stops I want it to continue on to the next record.
I first tried this:
DELETE FROM tblContact
WHERE sActiveFlag = 'F'
I then tried a cursor thinking I could check the error and continue but
it still stops:
DECLARE @.lContactId int
DECLARE cExchange SCROLL CURSOR FOR
select lContactId FROM tblContact
WHERE sActiveFlag = 'F'
order by lContactId
FOR READ ONLY
OPEN cExchange
FETCH FIRST FROM cExchange INTO
@.lContactId
WHILE @.@.FETCH_STATUS = 0
BEGIN
DELETE FROM tblContact
WHERE lContactId = @.lContactId
IF ( @.@.ERROR != 0 )
BEGIN
FETCH NEXT FROM cExchange INTO
@.lContactId
END
ELSE
BEGIN
FETCH NEXT FROM cExchange INTO
@.lContactId
END
select @.@.FETCH_STATUS, @.@.error
END
CLOSE cExchange
DEALLOCATE cExchange
Any help would be greatly appreciated.
Thanks,
DeidreDS wrote:
> I have a table that has about 10 different foreign key and trigger
> contraints. I am wanting to setup a delete that will delete records
> that do not have a contraint problem.
I suppose it's out of the question to just go through each constraint,
figure out what it means, and translate it into a WHERE subclause?
DBCC CHECKCONSTRAINTS('ttOrdClubItem') WITH ALL_CONSTRAINTS,
ALL_ERRORMSGS
may help.|||Thanks for the suggestion. I was trying not to do that because there
are so many contraints and some are around databases. Also this tables
has the potential to have alot more contraints added so I didn't want
to miss anything. Any other suggestions?|||Did you try disabling triggers and constraints?
alter table t1
nocheck constraint all
go
alter table t1
disable trigger all
go
delete ...
alter table t1
check constraint all
go
alter table t1
enable trigger all
go
AMB
"DS" wrote:

> Thanks for the suggestion. I was trying not to do that because there
> are so many contraints and some are around databases. Also this tables
> has the potential to have alot more contraints added so I didn't want
> to miss anything. Any other suggestions?
>|||If I disable the triggers and constraints wouldn't it then allow me to
delete the ones with contraints? I don't want to delete the ones with
contraints I want to skip those.
Deidre|||DS wrote:
> Thanks for the suggestion. I was trying not to do that because there
> are so many contraints and some are around databases. Also this tables
> has the potential to have alot more contraints added so I didn't want
> to miss anything. Any other suggestions?
After thinking it over some more, I realize that the DBCC command I
gave above is totally not what you want. You want to know which records
can be deleted without violating constraints; the DBCC command would
return which records are violating current constraints. Not the same
thing at all.
The only server-side solution I can think of is to use sp_execsql in a
cursor or some other loop:
DECLARE @.IContactId int
DECLARE @.returnStatus int
DECLARE cExchange SCROLL CURSOR FOR
select lContactId FROM tblContact
WHERE sActiveFlag = 'F'
order by lContactId
FOR READ ONLY
OPEN cExchange
FETCH FIRST FROM cExchange INTO @.lContactId
WHILE @.@.FETCH_STATUS = 0
BEGIN
EXECUTE @.returnStatus = sp_executesql
N'DELETE FROM tblContact WHERE lContactId = @.theID',
N'@.theID int',
@.IContactId
-- if @.returnStatus is 0, delete succeeded; if not, it's 1.
-- you could do something with that fact now, if needed
FETCH NEXT FROM cExchange INTO @.lContactId
END
Short of that, you'd have to do your looping from an external program.|||Good suggestion! I really thought that was going to work but it still
stops once it hits the first constaint problem. Ugh!!!

Monday, March 19, 2012

Deleting a Primary Key Constraint with TSQL

How do i delete a Primary Key constraint on a table using TSQL?You can use the alter table statement. For example:

ALTER TABLE TableName DROP CONSTRAINT PK_NAME

More info is located here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_aa-az_3ied.asp

Regards
Basia|||And what if the contraint has no name?
And what about IDENTITY, how do you drop that?

Thanks in advance!|||The constraint should have a name, use sp_help TableName to look it up.

Wednesday, March 7, 2012

Delete/truncate table ignoring contraints

Is there any easy way to truncate a table which has a foreign key restraint? I want to override the default behavior which is to not allow truncate of parent tables. I want to be able to temperarily remove the contraint so I can truncate the temple, how do you do this?

I should add that the systables keep track of the contraints. There should be a query that I could run that would just disable the checking of the contraint? Any help?|||No. There is no way to control/alter the behavior of truncate table. If you need to use it you have to drop the FK constraints even if the table is empty.|||

O.K. So... that isn't easily done.

Is there any easy way to simply copy the schema, contraints and everything but simply no data? Perhaps using DTS?

Or perhaps, is there another way to reset the identity information of a table? The delete operator does not reset identity.

|||If you want to reset identity value you can use DBCC CHECKIDENT. See Books Online for more details. Your original question was different.||| your original question was different

:) Thanks.

delete w/ foreign key question

Is there a way to see the locks associated with a delete statement on a table (tab1) that has 5 or 6 Foreign key relationships. Trying to understand the impact of the delete on concurrency There are several delete deadlocks on one of the foreign key tables (tab2) and the system does not delete from the table (tab2) that is throwing the delete deadlock error. Wondering about the impact of foreign keys on deletes on Tab1 on Tab2.

Didn't see anything in query analyzer that would show the actual locks. It seems to have scans or such but no lock levels etc are shown.

Does anyone have any knowledge of how to see the actual locks thrown by a given statement. The delete on Tab1 statement is very quick so using EM has proved fruitless.

MikeOh, such simple question but resolving blocking/deadlocking is really an art. You might want to start here.

http://support.microsoft.com/kb/224453

Saturday, February 25, 2012

Delete statement using a join plz help

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 helpDo I understand it right that you basically want to replace data in one DB with data from another database?

Friday, February 24, 2012

delete rows by checking conditions in more than one column

Hi All,

I have tables in three hierarchy...
I need to delete rows from the table which in 3rd level of hierarchy.

For ex: Table 1 has primary key col1.
Table 2 has primary key Col2 and Foreign key COL1 and
Table 3 has primary key Col3 and Foregn key Col2.

Now I have to delete all the rows in table three where Table3.Col2=Table2.Col2
and Table2.Col1=Table1.Col1

I could insert successfully using this condition but I am unable to delete.
I tried nested queries but it fails as the sub query returns more than one row.

Please help me how to overcome this.
An example is more helpful.

Thank you
Madhavi

Quote:

Originally Posted by madhavi123

Hi All,

I have tables in three hierarchy...
I need to delete rows from the table which in 3rd level of hierarchy.

For ex: Table 1 has primary key col1.
Table 2 has primary key Col2 and Foreign key COL1 and
Table 3 has primary key Col3 and Foregn key Col2.

Now I have to delete all the rows in table three where Table3.Col2=Table2.Col2
and Table2.Col1=Table1.Col1

I could insert successfully using this condition but I am unable to delete.
I tried nested queries but it fails as the sub query returns more than one row.

Please help me how to overcome this.
An example is more helpful.

Thank you
Madhavi


Please don't post questions in the articles section.
Moved to the forum.

Delete row from MS SQL Server 2000

Hi, I'm using SQL Server 2000 Personal Edition. I have created a table 'Student' which has 2 fields.

ID -- Varchar(10), Primary Key - contains ID of a student

NAME -- Varchar(50) -- contains names of student

ID NAME

0107200701 abcd

0107200702 cdgdh

0107200703 iyiylklk

.

.

I want to delete a complete row (all entries) from the "student" table using/specifing 'ID'. What will be the SQL query for that?

Hi

Try to use this (and please read help Wink )

delete from Student where [ID] = '0107200701'

You should change the ID to your real ID

Regards,

Janos

Sunday, February 19, 2012

Delete Records when you have a primary key of two Columns

Hi everyone.

I have two tables: the catalog table and the detail table.
The two tables are joined by a two-columns key.

I want to make a Delete sentence for delete all the rows in the Catalog table that aren't in the detail table, in SQL Server.

The only problem is that the key is composed by two colums.

If the Key was maded of one column, that would be easy, like this:

DELETE FROM CATALOG
WHERE CATALOGKEY NOT IN (SELECT CATALOGKEY FROM DETAIL)

But it is possible to make a delete sentence if the key has two columns ?

ThanksBut it is possible to make a delete sentence if the key has two columns ?But of course :)

DELETE
FROM CATALOG
WHERE NOT EXISTS
(SELECT *
FROM DETAIL
WHERE DETAIL.CATALOGKEY = CATALOG.CATALOGKEY
AND DETAIL.FIELD2= CATALOG.FIELD2)

hth|||I get a sense that something else is afoot...

Read the sticky at the top of the forum and post what it asks for

Friday, February 17, 2012

delete query ?

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,
SamIt is not valid SQL. Joins are only allowed in the FROM clause.

If you'd bothered to mention what you are trying to do it might have been possible to give some legal SQL that does it. :rolleyes:

Dag|||Your syntax is almost correct except for one too many FROMs and WHEREs:

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

delete query ?

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,
SamPlease ignore the above query, this is invalid, as I have type as 'd:key'. Please see my next post to this.

Delete problem

Dear all,

I have an asp.net webform which will provide delete function. If there are foreign key constraint and the user click the delete button, i would like the user to get response (Eg You must delete other data first......or something like this)

1. Any good idea?

2. One way i search from this form is like this, it raise error in db side(stored proc)

IF EXISTS (SELECT id FROM A WHERE ID = @.ID)
BEGIN
RAISERROR (''VersionA.)
RETURN
END

IF EXISTS (SELECT id FROM A WHERE ID = @.ID)
BEGIN
RAISERROR (''VersionB.)
RETURN
END

How can i get the raiseerror and identiy the veriosn of error in asp.net page?

Thanks in advance!!!!

Return a value to indicate that child records exists. Raising an error is not good idea due to performance.

|||This should already be taken care of from the sql side as long as youhave enforce constraits on for deleting and crud operations. Allyou have to do is catch the SQL errors and handle them from your aspxwhich isnt hard. Search handling sql errors from the codebehind. All you would have to do is handle the event and showjavascript to the user that you need to delete things.

DELETE problem

I have a hierarchy of menu and sub menus setup using this table:
CREATE TABLE menu
(
id INT NOT NULL IDENTITY PRIMARY KEY,
name VARCHAR(30)NOT NULL,
parentID INTNULL --Null If Root Menu
)

I want all sub menus to be deleted when a parent menu is deleted. I
wasn't able to get a recursive procedure to work because I got an error
about multiple cursors w/ the same name.

The best I've come up w/ is this:

DELETE FROM menu WHERE id = x --Del Menu
--Cleanup Children
DELETE FROM menu WHERE parentID <> NULL AND parentID NOT IN(SELECT id
from menu)

Is there a better/faster way of doing this?Hi

If you did not see my reply to your previous post, the following is about
the best you can do

DELETE FROM menu WHERE id = x --Del Menu

WHILE @.@.ROWCOUNT > 0
BEGIN
DELETE FROM menu
WHERE parentID IS NOT NULL
AND parentID NOT IN (SELECT id FROM menu)
END

Do not use <> NULL

John

<wackyphill@.yahoo.com> wrote in message
news:1103306757.201621.73930@.z14g2000cwz.googlegro ups.com...
>I have a hierarchy of menu and sub menus setup using this table:
> CREATE TABLE menu
> (
> id INT NOT NULL IDENTITY PRIMARY KEY,
> name VARCHAR(30) NOT NULL,
> parentID INT NULL --Null If Root Menu
> )
> I want all sub menus to be deleted when a parent menu is deleted. I
> wasn't able to get a recursive procedure to work because I got an error
> about multiple cursors w/ the same name.
> The best I've come up w/ is this:
> DELETE FROM menu WHERE id = x --Del Menu
> --Cleanup Children
> DELETE FROM menu WHERE parentID <> NULL AND parentID NOT IN(SELECT id
> from menu)
> Is there a better/faster way of doing this?|||John Bell wrote:
> Hi
> If you did not see my reply to your previous post, the following is
about
> the best you can do
> DELETE FROM menu WHERE id = x --Del Menu
> WHILE @.@.ROWCOUNT > 0
> BEGIN
> DELETE FROM menu
> WHERE parentID IS NOT NULL
> AND parentID NOT IN (SELECT id FROM menu)
> END
> Do not use <> NULL
> John
> <wackyphill@.yahoo.com> wrote in message
> news:1103306757.201621.73930@.z14g2000cwz.googlegro ups.com...
> >I have a hierarchy of menu and sub menus setup using this table:
> > CREATE TABLE menu
> > (
> > id INT NOT NULL IDENTITY PRIMARY KEY,
> > name VARCHAR(30) NOT NULL,
> > parentID INT NULL --Null If Root Menu
> > )
> > I want all sub menus to be deleted when a parent menu is deleted. I
> > wasn't able to get a recursive procedure to work because I got an
error
> > about multiple cursors w/ the same name.
> > The best I've come up w/ is this:
> > DELETE FROM menu WHERE id = x --Del Menu
> > --Cleanup Children
> > DELETE FROM menu WHERE parentID <> NULL AND parentID NOT IN(SELECT
id
> > from menu)
> > Is there a better/faster way of doing this?|||Thanks, John. That works great!|||Sorry John I did miss your last post and you are right, that works very
well. Thank you very much.|||Look up the nested sets model for trees; this can be done without
procedural code.

Tuesday, February 14, 2012

delete multi records

hi,
I found there are few records have duplicate key in my databaes,
for example, title table, have server same title, how to write a query, can
delete teh duplicate entries but only keep one. how to do this? Thanks in
advance.By what criteria would you want to delete rows from this table? Just because
multiple rows have the same TitleName, that doesn't mean that the entire row
is duplicated. You didn't say what the primary key is. If the table does not
have one, then implement that into your design after cleaning up the data.
The following query will return all rows from the Title table that have a
TitleName that is duplicated in another row. Once done, you can review the
list and identify specific rows to delete.
select
*
from
Titles
where
TitleName in
(
select
TitleName
from
Titles
group by
TitleName
having
count(*) > 1
)
"js" <js@.someone@.hotmail.com> wrote in message
news:Ow%23cX8VOGHA.1028@.TK2MSFTNGP11.phx.gbl...
> hi,
> I found there are few records have duplicate key in my databaes,
> for example, title table, have server same title, how to write a query,
> can delete teh duplicate entries but only keep one. how to do this? Thanks
> in advance.
>