Deleting Tablerecords With Multiple Childs(forign Keys) Using C#
Mar 1, 2004
i have a database sturcture :
| tbl_Customer | -> one to many ->| tbl_Orders |
What i want is to delete one customer from the tbl_Customer table, and automatically delete all the child orders to that customer.
i could by using loops, look through all the childs and delete the records one by one and the customer last.
so i wounder if there are an SQL state that automatically look up childs and drop them all by calling an stored procedure.
View 3 Replies
ADVERTISEMENT
Feb 3, 2008
I'm working with a SQL 2000 DB, which has a table structure as follows, implemented with foreign key constraints: ________________________________| ||--> TABLE1 --> TABLE2 --> TABLE3 --|
(ie, it forms a 'loop' so to speak)
I am trying to create a clean copy of this database, basically by deleting all the data in most of the tables, and these 3 tables are included. Of course, when I run a DELETE on any of these tables, it complains because of the FK. How can I script a delete on the 3 tables without manually deleting row after row, until there aren't anymore relations?
Cheers for any help :)
View 11 Replies
View Related
Apr 2, 2008
Is there a way to delete from multiple tables/views a column with a specificname? For example, a database has 50 tables and 25 views all have a columnnamed ColumnA. Is it possible to write a simple script that will deleteevery column named ColumnA from the database?Seems to be it would be possible and I can somewhat vision it usingsysobjects but without wanting to spend too much time generating the script(when I could in shorter time manually delete) thought I'd pose the question.Thanks.
View 2 Replies
View Related
Jan 2, 2007
Dear Sir,
I am working on mysql (linux). I cant add forign key to my tables.
ALTER TABLE test
ADD CONSTRAINT ldf_fk
FOREIGN KEY(lead_code)
REFERENCES source(lead_code)
regards
Joby
View 1 Replies
View Related
Apr 28, 2004
Hi all
i have one central site and 7 remote sites, there are one mssqlserver 2k in each sites.
i have to replicate 4 table in one DB(my DB have about 20 tables) in my 8 sites.
this 4 table have forignkey between themselves and other15 tables
i planed to transactional replication but i cant becuse forign keys occure erros
if needed i can send my DB digram to you.
can anyone help me? :confused:
Thanx
M.J.Danesh
View 1 Replies
View Related
Jun 25, 2004
What are the possible issues I could run in to having multiple foreign keys in a table. Here is why I ask. I have a db (sql server) that has a participant table, a forum table, and a forum reply table. Every record in the forum reply table is associated with the forum table via a PK-FK relationship w/cascading updates/deletes. The participants who post in these tables are not tied back to the participant table via a PK-FK relationship w/cascading updates/deletes. Should they be?
The problem I ran in to is that one particpant was deleted from the participant table but a post with their partid still existed in the forum or forum reply tables.
My feeling is that anytime a participant is deleted, everything that pertains to them should go too, right? If I am right, what do I have to be careful of if I do that?
Let me know! Thanks!!
View 1 Replies
View Related
Nov 20, 2004
I am constructing a db in sql server 2000 that will score cross-country running meets. I have an individual results table that needs to only contain participants that are entered as participants but are specific to a certain race as well. Can I have this table be linked back to TWO other tables via the PK-FK relationship and what issues might I have doing that?
Thanks!
View 5 Replies
View Related
Dec 30, 2004
I am having trouble creating multiple foreign keys on a table so that I can set up cascading update and cascading delete from two different primary tables. I am using the diagram to do this but when I try to save the diagram I get the following error.
ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]ALTER TABLE statement conflicted with COLUMN FOREIGN KEY constraint 'FK_IndResults_RaceData'. The conflict occurred in database 'VIRA', table 'RaceData', column 'RaceID'.
What would cause this to happen? Is it possible that I have records in the foreign table that do not transfer back to the primary table?
Thanks!
View 2 Replies
View Related
Jun 18, 2008
Hi Guys,
Can someone tell me what is the best way to check 2 tables lets say tb1 and tb2, to find those customers that are in tb1 but not in tb2 using four fields(cardno,spend,date,refno) as the primary key. Duplicates fields are in tb1
View 3 Replies
View Related
Feb 12, 2003
I need to delete multiple sql logins on one of my database servers that are no longer needed. Most of these logins are not attached to any database on the server because the database has been deleted from this server. Is there any way to delete logins that are no longer needed without having to review every login to verify it is not attached to a database before deleting?
View 2 Replies
View Related
Aug 27, 2004
I have a table with a record that looks like the attached TXT.
I need to keep the most recently entered value where flag_out = 1 and delete those duplicate
records, and this should only apply to records where there's also an flag_in value of 1.
I've tried a bunch of delete statements without avail....
TIA
View 3 Replies
View Related
Sep 5, 2007
Hi,
How do you delete multiple packages at once ?
We have a folder in SSIS called ETL and there are about 25 SSIS packages in it.
Now we need to update it.
I tried to delete the folder but you get the message that the folder is not empty.
So I renamed the folder to ETL_old and my deployement works fine.
But now I want to get rid of all the old folders. Delete a folder didn't work.
Selecting multiple packages doesn't work.
To delete a single one you select the package, right click and select delete, click yes.
But then I have to do it 25 times. I was unable to set a short cut with the keyboard for that action.
Any ideas ?
Constantijn Enders
View 1 Replies
View Related
Oct 11, 2006
Hi, from the "best practice" perspective, how convenient is to use multiple field primary keys in a table, how convenient is it to replace a multifield pk with an autoincrement field to represent such a table?
I tried using a calculated field product of appending the fields that cvompose the primary key, but MySQL for example, does not provide with that functionality, which makes me wonder it doing so in SQL Server is a good practice at all.
Thank you
View 1 Replies
View Related
Apr 19, 2005
want to delete rows from two tables after a join.
in Access, here's something we can do:
delete table_A.*, table_B.*
from table_A left join table_B on ...
but in ms sql, it appears (to me) that you can only delete from one table at a time. how would i accomplish what i want to do?
also, is there a distinctrow equivalent in ms sql server? thanks
View 3 Replies
View Related
Jan 10, 2007
I have 3 tables . iwant to delete rows from all the three tables at same time using single statement.All the 3 tables have a unique column which will be supplied ny the user.
DELETE FROM T1,T2,T3 WHERE column1='1'
how do i do it.
View 4 Replies
View Related
Feb 28, 2007
Hey all,
I know very simple SQL queries but I need help with this one. I have multiple lines in a SQL database that I need to run. Basically, I need to run this (the bracketed text and the XXX are place holders):
DELETE FROM [tableName] WHERE [columnName] = 'XXXXX'
But I need to run it around 90 times where XXXXX is a unique variable each time. I could create 90 lines similar to this one but that would take way too much time to run. Any suggestions for a noob?
Thanks,
- MT
-=<>=-=<>=-=<>=-=<>=-=<>=-
Matt Torbin
President
Center City Philadelphia Macintosh Users Group
http://www.ccpmug.org/
View 3 Replies
View Related
Oct 13, 2014
I have sp that works with GUI and have an opton for sort field/ collation. But I noteiced that if I do level on very generic key like <Level> in my case it does the job, but output does'nt look right after that all names, account numbers are messed, so I'd like to add second sort column and looks like it can'be be done with my syntax, I tried to play adding second column and failed.
Select * from T1 order by Level, FirstName
Looks like it only can be done with Dynamic...
DECLARE @SortColmn VARCHAR(10) = 'Level'
SELECT *
FROM TABLE
CASE WHEN @SortColmn = 'FirstName' AND @SortDir = 0 THEN FirstName END DESC
,CASE WHEN @SortColmn = 'LastName' AND @SortDir = 0 THEN LastName END DESC
,CASE WHEN @SortColmn = 'Region ' AND @SortDir = 0 THEN Region END DESC
,CASE WHEN @SortColmn = 'Level' AND @SortDir = 0 THEN [Level] END desc --<@>>< THEN FIrstName asc ???
View 1 Replies
View Related
Jul 23, 2005
Hi All,I'm trying to solve this for a few days now and I just can't figure itout...I have three tables set up, I'll simplify them for this question:Table 1: HOTELSColumns: HOTEL_ID, HOTEL_NAMEExmple row: 123 || 'Hotel X'Table 2: SERVICESColumns: SERVICE_ID, SERVICE_NAMEExample rows:1 || 'Breakfast in bed'2 || 'King size bed'Table 3: LINK_HOTELS_SERVICESColumns: FK_HOTEL_ID, FK_SERVICE_ID, SERVICE_VALUEExample rows:123 || 1 || 1123 || 2 || 1In table 3 I link different services to different hotels. In the same tableI set the "value" for the service.The first example row of table 3 means something like: Hotel X offersBreakfast in bed. In this case 1 stands for TRUEThe second example row of table 3 means: Hotel X offers King size beds(again: 1 stands for TRUE).What I'm struggling with is selecting the hotel ID's which offer multipleservices. To stay in the example: how can I select all hotels whereSERVICE_ID = 1 AND SERVICE_ID = 1. I can't seem to figure out how to doit...I hope anyone can help... Thanks a lot in advance!!!Robert
View 2 Replies
View Related
Jul 23, 2005
I have a table which has 10 columns which make up the secondary key. 1or more of these columns can be set but the remaining columns in thesecondary key will be null. For example :id k1 k2 k3 k4 k5 k6 k7 k8 k9 k10 data-------------------------------------------------0 1 1 - - - - - - - - test01 1 1 1 - - - - - - - test12 1 1 2 - - - - - - - test23 1 1 3 - - - - - - - test34 1 1 3 1 - - - - - - test45 1 2 1 - - - - - - - test56 1 2 2 - - - - - - - test6Each row represents a node in a tree structure, the secondary keycolumns point to which node in the tree. The above example has onenode in tree branch 1, three nodes in tree branch 1-1, one node inbranch 1-1-3 and two nodes in branch 1-2.My question is how can I write a single stored procedure to returnonly the nodes in a given tree branch without needing logic based onlooking for NULL parameters. I have written the stored procedurebelow. If I want to retrieve all nodes in branch 1-1 (ie; test1, test2and test3) then I want be able to call :execute "mysp Test" 1, 1But this only returns a single record, test0. The reason for this isobvious if you look at the stored procedure. What I really need is wayof sayingexecute "mysp Test" 1, 1, NOT NULLso that it returns all records in branch 1-1 where Key3 is NOT NULLbut all subsequent keys are null, ie; Key4-Key10 are NULL. The storedprocedure must work with any number of secondary keys though, so Icould use it to call :execute "mysp Test" 1, 1, 3, NOT NULLwhich would retrieve test4.Can anybody help me out here?Thanks for reading.Here's the stored procedure as it stands :CREATE PROCEDURE [dbo].[mysp Test]( @key1 smallint,@key2 smallint=NULL,@key3 smallint=NULL,@key4 smallint=NULL,@key5 smallint=NULL,@key6 smallint=NULL,@key7 smallint=NULL,@key8 smallint=NULL,@key9 smallint=NULL,@key10 smallint=NULL ) ASselect * from TreePositionTestwherekey1=@key1 andkey2=@key2 andkey3=@key3 andkey4=@key4 andkey5=@key5 andkey6=@key6 andkey7=@key7 andkey8=@key8 andkey9=@key9 andkey10=@key10GO
View 3 Replies
View Related
Jul 23, 2005
Hey,I am having some confusion about how to formulate this particularquery.I have 2 tables. Table A has 4 columns say a1,a2,a3,a4 with thecolumns a1,a2,a4 forming the primary key. Table B again has 3 columnswith b1,b2,b3,b4 and like before, b1,b2 and b4 form the primary key.All columns are of the same datatype in both tables. Now I want to getrows from table A which are not present in table B. Whats the best wayof doing this?Thanks--Posted using the http://www.dbforumz.com interface, at author's requestArticles individually checked for conformance to usenet standardsTopic URL: http://www.dbforumz.com/General-Dis...pict235166.htmlVisit Topic URL to contact author (reg. req'd). Report abuse: http://www.dbforumz.com/eform.php?p=815725
View 6 Replies
View Related
Apr 18, 2006
Table partitioning with multiple key coulmns
Hi champs!
I have one table with around 600 million records.
I want to partition this table on 5 different coulumns.
year, month. coulumn3, coulumn4 and coulumn5.
How do I do this best?
What is the best way of doing this; is there any best practice on ths?
The obvious thing is to make a partition funktion based on the year and month coulmns, but I also want to partition on coulumn3, coulumn4 and coulumn5.
Many thanks
Kurlan
View 1 Replies
View Related
Mar 1, 2005
Hi,
I'm using ASP with a JScript variant and MSSQL Server 2000. I would like to write a script that basically erases all data except for a few things.
Is there a way to update multiple tables at once without having to write lines and lines of code? I tried UPDATE tbl1,tbl2 SET uid='asc', but to no avail. It gave me a syntax error. My thinking behind it is something like... UPDATE dbo.* SET uid='mferguson' and after that I can delete stuff like DELETE dbo.*... Any ideas?
I know the above is ASP, I've tried this thread in the ASP forum with no avail... they referred me to this forum.
View 1 Replies
View Related
Oct 10, 2007
Hi,
I have different tables with the same schema as follows
ID Name
-----------------
<Table 1>
ID Name
-------------------
1 Name1
2 Name2
3 Name3
<Table 2>
ID Name
-------------------
1 Name1
4 Name4
5 Name5
I just want to delete the row where ID = 1 from these tables in one query ? Is it possible??
Thanks
~Mohan
View 6 Replies
View Related
Jun 8, 2007
Hi All
I'm new to sql server. I have built simple database apps using MFC CRecordset over MS Access. I'm tying to learn about SQL server by building a simple app using MFC CRecordset in Visual Studio 2005.
The problem I have is within SQL Server Management studio experess. I have a table called OriginalDrawings that looks like this
CREATE TABLE [dbo].[OriginalDrawings](
[DrawingID] [int] IDENTITY(1,1) NOT NULL,
[OriginalFileName] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[PartNumber] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[SheetNumber] [int] NULL,
[Revision] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
[OriginalDirectory] [varchar](100) COLLATE Latin1_General_CI_AS NULL,
[DrawingCategory] [int] NOT NULL,
[ProductFamily] [int] NOT NULL,
[IsSalvage] [bit] NULL,
[FileSize] [int] NULL,
[DataQueryFlag] [bit] NOT NULL,
[DataQueryCode] [int] NULL,
CONSTRAINT [PK_OriginalDrawings] PRIMARY KEY CLUSTERED
(
[DrawingID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
I've loaded it with 40,000 records from my test app. If I open it in SSMSE hit Ctrl-A to select all and then press delete SSMSE appears to hang - it freezes for 10 mins+ (after which I restart my PC. I can delete 1000 records at a time OK, I can delete all quite quickly from my test app by walking through the recordset and deleting each record.
Does anyone know why it appears to hang when I try the delete all?
Thanks
Alec
SQL Server 2005 Express 9.00.3042.00
Microsoft SQL Server Management Studio Express 9.00.2047.00
Microsoft Data Access Components (MDAC) 2000.085.1117.00 (xpsp_sp2_rtm.040803-2158)
Microsoft MSXML 2.6 3.0 4.0 5.0 6.0
Microsoft Internet Explorer 6.0.2900.2180
Microsoft .NET Framework 2.0.50727.42
Operating System 5.1.2600
View 1 Replies
View Related
Jul 13, 2007
I'm new to relational database concepts and designs, but what i've learned so far has been helpful. I now know how to select certain records from multiple tables using joins, etc. Now I need info on how to do complete deletes. I've tried reading articles on cascading deletes, but the people writing them are so verbose that they are confusing to understand for a beginner. I hope someone could help me with this problem.
I have sql server 2005. I use visual studio 2005. In the database I've created the following tables(with their column names):
Table 1: Classes --Columns: ClassID, ClassName
Table 2: Roster--Columns: ClassID, StudentID, Student Name
Table 3: Assignments--Columns: ClassID, AssignmentID, AssignmentName
Table 4: Scores--StudentID, AssignmentID, Score
What I can't seem to figure out is how can I delete a class (ClassID) from Classes and as a result of this one deletion, delete all students in the Roster table associated with that class, delete all assignments associated with that class, delete all scores associated with all assignments associated with that class in one DELETE sql statement.
What I tried to do in sql server management studio is set the ClassID in Classes as a primary key, then set foreign keys to the other three tables. However, also set AssignmentID in Table 4 as a foreign key to Table 3.
The stored procedure I created was
DELETE FROM Classes WHERE ClassID=@classid
I thought, since I established ClassID as a primary key in Classes, that by deleting it, it would also delete all other rows in the foreign tables that have the same value in their ClassID columns. But I get errors when I run the query. The error said:
The DELETE statement conflicted with the REFERENCE constraint "FK_Roster_Classes1". The conflict occurred in database "database", table "dbo.Roster", column 'ClassID'.
The statement has been terminated.
What are reference constraints? What are they talking about? Plus is the query correct? If not, how would I go about solving my problem. Would I have to do joins while deleting?
I thought I was doing a cascade delete. The articles I read kept insisting that cascade deletes are deletes where if you delete a record from a parent table, then the rows in the child table will also be deleted, but I get the error.
Did I approach this right? If not, please show me how, and please, please explain it like I'm a four year old.
Further, is there something else I need to do besides assigning primary keys and foreign keys?
View 6 Replies
View Related
May 26, 2007
is there a way to delete multiple tables using the Management Studio GUI?
View 1 Replies
View Related
Feb 1, 2007
Hi,
I am trying to execute following sql script in sql-server 2000 query analyzer
CREATE TABLE user_courses (user_id varchar(30) NOT NULL PRIMARY KEY,
course_id varchar(10) NOT NULL PRIMARY KEY)
Its give's me following error :-
Cannot specify multiple primary key constraint
Hence I am not able to ceate table with multiple primary keys. So can any one tell me how to get this done?.
Secondly, Primary key must be unique i.e duplicate values are not allowed in P.K field. But in this case since I am declaring two fileds as primary keys.
Will it allow me to have following records in the user_courses table?
user_id(P.K) course_id(P.K)
bob CRS235
alice CRS235
Tim CRS235
tom CRS635
So, if we consider both the fields as primary keys together than I am not voilating Uniqueness constraint. But, if I look at course_id alone then I am voilating uniqeness property?
Thanks,
View 4 Replies
View Related
Mar 31, 2008
I have a database in XML format , with 100+ tables, that I want to import into SQL server but the problem is that I don't have any of the original primary key information. I know that some of the tables had multiple primary keys.
Is there a method or a tool that is capable of determining the primary keys for me??
I don't want to have to figure it out by hand, especially if I have more of these databases in the future.
View 4 Replies
View Related
Feb 21, 2007
Hi,
I'm trying to create a DM model using TS algorithm, to predict sales for different products and channels but I can only get it to work using one of those two "dimensions" or columns the other one is ignored (This is, my fact table contains a key for time, a key for channel a key for product and the metrics and the model only seems to allow working with time, the metrics and only one of the other dimensions product or channel ..) Am I missing something?
Thanks
View 1 Replies
View Related
Jul 24, 2007
Hi,
I have a relational database with the primary table, table01. And 2 child/foreign tables, table02 and table03. All 3 tables shared the same key - [ID].
I am not sure if this is the correct approach but I am trying to create a stored procedure where if I were to delete a the row in table01 (primary), the procedure will automatically delete the common row in both table02 and table03.
I have come up with something like that but it does not seems to be correct.
CREATE PROCEDURE [sp_delete_test01_1] (@id [int])
AS
DELETE [test01] DELETE [test02] DELETE [test03]
WHERE ( [id] = @id)GO
Your advise please. Many Thanks.
View 4 Replies
View Related
Mar 19, 2012
I am developing a BI solution on SQL Server 2008 R2 and how to handle multiple referances to the same dimension from a fact table!
Here is the scenario;
Fact_Contracts (# M)
ServiceProvider_CompanyID, Client_CompanyID, Amount_USD
Dim_Company( hundreds)
ID, CityID, ProfessionID, CompanyName
Dim_City
ID, CityName
Dim_Profession
ID, ProfessionName
As u can see there is two company references in my fact table, and the schema is in snowflake. My customer requirements state that the Contracts' amounts can be aggregated/filtered for/by, ServiceProviderCompany, its city/profession or ClientCompay, its city/profession.
First thing came in to my mind is to dublicate whole dimension structure (one for serviceproviders, one for clients), which i thought that there should be another way around?
View 5 Replies
View Related
Apr 11, 2006
Hello again,
I'm going through my tables and rewriting them so that I can create relationship-based constraints and create foreign keys among my tables. I didn't have a problem with a few of the tables but I seem to have come across a slightly confusing hiccup.
Here's the query for my Classes table:
Code:
CREATE TABLE Classes
(
class_id
INT
IDENTITY
PRIMARY KEY
NOT NULL,
teacher_id
INT
NOT NULL,
class_title
VARCHAR(50)
NOT NULL,
class_grade
SMALLINT
NOT NULL
DEFAULT 6,
class_tardies
SMALLINT
NOT NULL
DEFAULT 0,
class_absences
SMALLINT
NOT NULL
DEFAULT 0,
CONSTRAINT Teacher_instructs_ClassFKIndex1 FOREIGN KEY (teacher_id)
REFERENCES Users (user_id)
)
This statement runs without problems and I Create the relationship with my Users table just fine, having renamed it to teacher_id. I have a 1:n relationship between users and tables AND an n:m relationship because a user can be a student or a teacher, the difference is one field, user_type, which denotes what type of user a person is. In any case, the relationship that's 1:n from users to classes is that of the teacher instructing the class. The problem exists when I run my query for the intermediary table between the class and the gradebook:
Code:
CREATE TABLE Classes_have_Grades
(
class_id
INT
PRIMARY KEY
NOT NULL,
teacher_id
INT
NOT NULL,
grade_id
INT
NOT NULL,
CONSTRAINT Grades_for_ClassesFKIndex1 FOREIGN KEY (grade_id)
REFERENCES Grades (grade_id),
CONSTRAINT Classes_have_gradesFKIndex2 FOREIGN KEY (class_id, teacher_id)
REFERENCES Classes (class_id, teacher_id)
)
Query Analyzer spits out: Quote: Originally Posted by Query Analyzer There are no primary or candidate keys in the referenced table 'Classes' that match the referencing column list in the foreign key 'Classes_have_gradesFKIndex2'. Now, I know in SQL Server 2000 you can only have one primary key. Does that mean I can have a multi-columned Primary key (which is in fact what I would like) or does that mean that just one field can be a primary key and that a table can have only the one primary key?
In addition, what is a "candidate" key? Will making the other fields "Candidate" keys solve my problem?
Thank you for your assistance.
View 1 Replies
View Related
Jul 16, 2014
what the best practice is for creating indexes on columns that are foreign keys to the primary keys of other tables. For example:
[Schools] [Students]
---------------- -----------------
| SchoolId PK|<-. | StudentId PK|
| SchoolName | '--| SchoolId |
---------------- | StudentName |
-----------------
The foreign key above is as:
ALTER TABLE [Students] WITH CHECK ADD CONSTRAINT [FK_Students_Schools]
FOREIGN KEY([SchoolId]) REFERENCES [Schools] ([SchoolId])
What kind of index would ensure best performance for INSERTs/UPDATEs, so that SQL Server can most efficiently check the FK constraints? Would it be simply:
CREATE INDEX IX_Students_SchlId ON Students (SchoolId)
Or
CREATE INDEX IX_Students_SchlId ON Students (SchoolId, StudentId)
In other words, what's best practice for adding an index which best supports a Foreign Key constraint?
View 4 Replies
View Related