Search On Table With Recursive Relationship

Apr 15, 1999

I am using tables with recursive relationships extensively. For example the table tbComponent has a primary key called Co_ID and a foreign key called Co_Co_ID which references the field Co_ID. This allows a component to have unlimited child components, and each child component can have an unlimited number of tiers of children. I have a few question for which I have seen no documentation on.

1. How can I create a view or a SP that will return a component record and all of its children and children's children records down to the last/lowest child record?

2. I need to be able to do a search in this table. Example:

Table: tbComponent
Columns: Co_ID Integer
Co_Co_ID Integer
Co_Name Text
Co_Attribute Text
Co_Category Text


Note: the data for Co_Category comes from a lookup table with also has a recursive relationship to itself where a category can have an unlimited number of tiers of children categories.

A typical group of records could be something like this:


Co_ID Co_Co_ID Co_Name Co_Attribute Co_Category

1 1 Car Blue Ford
2 1 Body Steel Parts
3 2 Door Front Parts
4 3 Invoice April 1 1999 Accounting

Ok, say there is over a million records in this table. Say I want to query this table and return all of the invoices for cars between March 1 1999 and May 1 1999. Say for example that there are less records where Co_Name has a value of Car then there are records with a value of Invoice, so logically I would set some kind of criteria to limit only invoices with where Co_Name = "Car". That's easy, I can return a result set of all the records Where Co_Name = "Car" and I can hold these in a view or a temp table. Now I need to query this View or temp table and see if it has any children records records Where Co_Name = "Invoice" . The problem is that the Invoice child could be a child record directly under the "Car" record, or 10 levels of children records down. The logic for this would be:

If Co_Name = "Car" Then Select * Where Co_Co_ID = 1, then take all of those record's values in Co_ID and run another statement Where Co_Co_ID = X and so on until there are no more children to search. If any of those records have a value of Invoice in Co_Name then return them.

Please don't give any speeches on Normal Relationship Database design suggesting a typical design using something like a Car table, a parts table, and a invoice table. I used the example above to demonstrate the dynamics of doing a search on a recursive relationship. I understand relationship theory and a recursive relationship is what we need to use in our situation.

Thanks for any and all input!

View 1 Replies


ADVERTISEMENT

Create Table With Recursive Relationship

May 16, 2006

I am fairly new to SQL and I am currently trying to createa SQL table (using Microsoft SQL) that has a recursiverelationship, let me try to explain:I have a piece of Data let's call it "Item" wich may again contain onemore "Items". Now how would I design a set of SQL Tables that arecapable of storing this information?I tried the following two approaches:1.) create a Table "Item" with Column "ItemID" as primary key, somecolums for the Data an Item can store and a Column "ParentItemID". Iset a foreign key for ParentItemID wich links to the primarykey"ItemID" of the same table.2.) create separate Table "Item_ParentItem" that storesItemID-ParentItemID-pairs. Each column has a foreign key linked toprimary key of the "Item" Column "ItemID".In both approaches when I try to delete an Item I get an Exceptionsaying that the DELETE command could not be executed because itviolates a COLUMN REFERENCE constraint. The goal behind these FK_PKrelations is is that when an Item gets deleted, all childItems shouldautomatically be deleted recursively.How is this "standard-problem" usually solved in sql? Or do I inned toimplement the recursive deletion myself using storedprocedures or something ?

View 3 Replies View Related

Recursive Relationship Query

May 21, 2006

Hi all,

Im really confused and need some help please from some of you clever people.

I know the basics of SQL but Ive no idea how to write a query to do this.

Basically, we have two tables, the first containing a list of people and the second containing two relationships to the person table. The first is the parent relationship and the second the child relationship. Each person may be related to one or more other people (e.g. father, son, brother, sister etc.). If you can imagine we have a few hundred people in the person going back a couple of hundred years.

Now Ive set the scene Im really trying to create a query that can navigate all the relationships from a set point (Person).

Ultimately I would like to (given a PersonID, navigate the full PERSON_ASSOCIATION table to find:

a. All people below the PersonID (if there are any)
b. All people above the PersonID (if there are any)

For example, in the data below there is somebody called John Smith.

Going down the PERSON_ASSOCIATION table I would like to show:

John Smith has a brother called Andrew Jones who has a brother-in-law called Stephen Barnes

John Smith has a wife called Jane Wallace

John Smith has a daughter called Mary Joseph

What I am going round in circles on is the multiple relatationships, e.g. A is related to B who in turn is related to D who in turn is related to E therefore A is related to E.




PERSON
ID NAME
1 John Smith
2 Andrew Jones
3 Jane Wallace
4 Steven Barnes
5 Mary Joseph
98 Me
99 Joanne




PERSON_ASSOCIATION
ID PARENT_PERSON_ID CHILD_PERSON_ID RELATIONSHIP
1 1 2 Brother
2 1 3 Wife
3 1 5 Daughter
4 2 4 Brother-In-Law
5 98 1 Father
6 98 99 Husband


Can somebody please point me in the right direction by explaining how I can write some SQL that will navigate (and iterate through) all the PERSON and PERSON_ASSOCIATION tables.

Im sure there must be a straight forward way of doing this.

One final thing, if it helps, Im hoping to eventually end up with a stored procedure which I can basically pass in a PERSON_ID and it returns a list of all the relationships from that person.

MANY BIG thanks in advance

Im really sorry but it is driving me crazy

Mike

View 1 Replies View Related

Selecting All Items In A Recursive Relationship

Feb 21, 2007

Hello

I'm having trouble writing a query that references a join to a table with a recursive relationship in a SQL Server 2005 database.

I have a list of products in Table1.
Each product belongs to a Category.
Categories are stored in Table2 which has a self-referencing relationship that forms a hierarchical list of categories and sub-categories.
Like so...
||-ID-||-Name-||-Parent-||
||1 ||Cat1-----||Null-----||
||2 ||Cat2-----||Null-----||
||3 ||Cat3-----||1-------||
||4 ||Cat4-----||1-------||
||5 ||Cat5-----||2-------||
||6 ||Cat6-----||2-------||
||7 ||Cat7-----||3-------||

What I'm trying to do is write a sproc that will pull down all products that belong to a particular category or any of it's sub-categories.

I managed to write a sproc that could handle two levels of category by using union to join two queries together but I don't know how to handle an n-tier hierarchical structure.

Can you point me in the right direction?

Many Thanks

View 2 Replies View Related

Recursive Search

Jun 5, 2002

Hi,
I have a table with 2 fields in it Circuit_ID and Parent_Circuit_ID and I'd like to pass a stored procedure a circuit_ID and get a resultset back of all Circuit_ID's that are associated with the original.

That means it needs to look at each record and do another search on all circuits that have that parent ID, recursively.

Does anyone have any good ideas on the best way to do this.

Appreciate any help.

Steve

View 1 Replies View Related

Transact SQL :: Types Don't Match Between Anchor And Recursive Part In Column ParentID Of Recursive Query

Aug 25, 2015

Msg 240, Level 16, State 1, Line 14

Types don't match between the anchor and the recursive part in column "ParentId" of recursive query "tmp". Below is query,

DECLARE @TBL TABLE (RowNum INT, DataId int, DataName NVARCHAR(50), RowOrder DECIMAL(18,2) NULL, ParentId INT NULL)
INSERT INTO @TBL VALUES
(1, 105508, 'A', 1.00, NULL),
(2, 105717, 'A1', NULL, NULL),
(3, 105718, 'A1', NULL, NULL),
(4, 105509, 'B', 2.00, NULL),
(5, 105510, 'C', 3.00, NULL),
(6, 105514, 'C1', NULL, NULL),

[code]....

View 2 Replies View Related

How To Convert Recursive Function Into Recursive Stored Procedure

Jul 23, 2005

I am having problem to apply updates into this function below. I triedusing cursor for updates, etc. but no success. Sql server keeps tellingme that I cannot execute insert or update from inside a function and itgives me an option that I could write an extended stored procedure, butI don't have a clue of how to do it. To quickly fix the problem theonly solution left in my case is to convert this recursive functioninto one recursive stored procedure. However, I am facing one problem.How to convert the select command in this piece of code below into an"execute" by passing parameters and calling the sp recursively again.### piece of code ############SELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uid######### my function ###########CREATE FUNCTION Mkt_GetChildren(@uid int, @subtotal decimal ,@DateStart datetime, @DateEnd datetime)RETURNS decimalASBEGINIF EXISTS (SELECTuidFROMcategories WHEREParentID = @uid)BEGINDECLARE my_cursor CURSOR FORSELECT uid, classid5 FROM categories WHERE parentid = @uiddeclare @getclassid5 varchar(50), @getuid bigint, @calculate decimalOPEN my_cursorFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5WHILE @@FETCH_STATUS = 0BEGINFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5select @calculate = dbo.Mkt_CalculateTotal(@getclassid5, @DateStart,@DateEnd)SET @subtotal = CONVERT (decimal (19,4),(@subtotal + @calculate))ENDCLOSE my_cursorDEALLOCATE my_cursorSELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uidENDRETURN @subtotalENDGORod

View 4 Replies View Related

SQL Search :: Full Text Search Of PDF Files In A File Table

Mar 30, 2013

I have installed the Adobe iFilter 11 64 bit and set the path to the bin folder. I still cannot find any text from the pdf files. I suspect I am missing something trivial because I don't find much when I Bing for this so it must not be a common problem.Here is the code.

--Adobe iFilter 11 64 bit is installed
--The Path variable is set to the bin folder for the Adobe iFilter.
--SQL Developer version 64 bit on both Windows 7 and Windows 8.
USE master;
GO
DROP DATABASE FileTableStudy;
GO
CREATE DATABASE FileTableStudy
ON PRIMARY

[code]....

View 14 Replies View Related

SQL 2012 :: FullText Search - Can Search Terms Come From Another Table

Mar 25, 2015

I have a table that contains words that will be used to search another table where FullText index has been created on searchable columns. I'm basically trying to run something like this:

SELECT t1.col1, t2.col3
FROM tbl1 t1, tbl2 t2
WHERE CONTAINS (t1.col1, t2.col1)

I know this won't work but is there a way to join these two tables so the words (t2.col1) can be passed as search conditions? There is no common key on both tables so normal join won't work. I'm trying to find a way to pass the search words from one table to another.

View 0 Replies View Related

Why I Got The Message As You Need To Create The Many-to-one Relationship Between The Case Table And The Nested Table?

May 30, 2007

Hi, all experts here,



Thank you very much for your kind attention.



I am trying to create a new mining structure with case table and nested table, the case table (fact table) has alread defined the relationships with the nested table(dimension table), and I can see their relationship from the data source view. But why the wizard for creating the new mining structure showed that message? Why is that? And what could I try to fix it?

Hope it is clear for your help.

Thanks a lot for your kind advices and I am looking forward to hearing from you shortly.

With best regards,

Yours sincerely,

View 4 Replies View Related

Recursive Data From Two Different Table

Oct 2, 2007

Hi All,

Im trying to retrieve multiple recursive data from two different columns with different conditions.

This is what I wrote.

WITH days15CTE AS
(
SELECT Days = 'From 1 to 15 Days'
, Num_Loans = count(DISTINCT AccountID)
, PBO = sum(Balance)

FROM Loan
WHERE CommencedOn >= GETDATE() - 15
, Loanstatus = Status
FROM LoanApplication

WHERE Status = 'Deliquent'

)
, days30CTE AS

and rest...........


But I get this error message.

There is an error in the query. Incorrect syntax near ','.
Incorrect syntax near ','.
Incorrect syntax near ','.

Can any body let me know where I went wrong please?

View 5 Replies View Related

How Can I Create A One-to-one Relationship In A SQL Server Management Studio Express Relationship Diagram?

Mar 25, 2006

How can I create a one-to-one relationship in a SQL Server Management Studio Express Relationship diagram?

For example:
I have 2 tables, tbl1 and tbl2.

tbl1 has the following columns:
id {uniqueidentifier} as PK
name {nvarchar(50)}

tbl2 has the following columns:
id {uniqueidentifier} as PK
name {nvarchar(50)}
tbl1_id {uniqueidentifier} as FK linked to tbl1.id


If I drag and drop the tbl1.id column to tbl2 I end up with a one-to-many relationship. How do I create a one-to-one relationship instead?

mradlmaier

View 3 Replies View Related

Power Pivot :: Use Relationship Not Overriding Conflicting Active Relationship?

Oct 14, 2015

I have four tables with relationships as shown. They have a circular relationship and so one of the relationships is forced to be inactive.

   Operation (Commodity, OperationKey)   ==========> 
Commodity (Commodity)
                      /                                                                        
/
                       |                                                                         
|
   Advice (OperationKey)       ====== (inactive)=======>
Operation Commmodity (Commodity, OperationKey)

I have the following measure:

Advice No. Commodity:=CALCULATE (
COUNTROWS ( 'Advice' ),
USERELATIONSHIP(Advice[OperationKey],'Operation Commodity'[OperationKey]),
operation
)

However, the userelationship function does not override the active relationship between Operation & Advice and so the measure is limited to Advices directly filtered by the Operation table.

If I delete the relationship between Operation and Advice, then the measure works as expected i.e. Operation indirectly filters Operation Commodity which filters Advice.

View 9 Replies View Related

Recursive Common Table Expression Data?

Jan 10, 2014

With my new data, need result for below scenario ( use CTE )

´`````````````
CREATE TABLE
´´´´´´´´´´´´´´´´
CREATE TABLE [dbo].[Travel_Master](
[Load_Id] [int] NULL,
[Mode_Id] [nchar](2) NULL,
[Mode_Info] [nchar](10) NULL,

[Code] ....

===============================
Insert DATA TABLE 1
===============================

INSERT INTO [dbo].[Travel_Master] ([Load_Id] ,[Mode_Id] ,[Mode_Info] ,[Has_Nodes]) VALUES ( 1,'AP' ,'AIR' ,'Yes')
INSERT INTO [dbo].[Travel_Master] ([Load_Id] ,[Mode_Id] ,[Mode_Info] ,[Has_Nodes]) VALUES ( 1,'FL' ,'FLIGHT' ,'Yes')
INSERT INTO [dbo].[Travel_Master] ([Load_Id] ,[Mode_Id] ,[Mode_Info] ,[Has_Nodes]) VALUES ( 1,'FP' ,'FLIGHT-Pas' ,'No')
INSERT INTO [dbo].[Travel_Master] ([Load_Id] ,[Mode_Id] ,[Mode_Info] ,[Has_Nodes]) VALUES ( 1,'SE' ,'SEA' ,'Yes')
INSERT INTO [dbo].[Travel_Master] ([Load_Id] ,[Mode_Id] ,[Mode_Info] ,[Has_Nodes]) VALUES ( 1,'SP' ,'SHIP' ,'No')
INSERT INTO [dbo].[Travel_Master] ([Load_Id] ,[Mode_Id] ,[Mode_Info] ,[Has_Nodes]) VALUES ( 1,'RD' ,'ROAD' ,'No')
INSERT INTO [dbo].[Travel_Master] ([Load_Id] ,[Mode_Id] ,[Mode_Info] ,[Has_Nodes]) VALUES ( 1,'BU' ,'BUS' ,'No')

===============================
Insert DATA TABLE 2
===============================
INSERT INTO [Travel_Quantity]([Load_Id],[Mode_Sno],[Mode_Id],[Mode_Parent_Sno],[QA]) VALUES ( 1,'1' ,'AP' ,'-1','4' )
INSERT INTO [Travel_Quantity]([Load_Id],[Mode_Sno],[Mode_Id],[Mode_Parent_Sno],[QA]) VALUES ( 1,'2' ,'FL' ,'1','2' )
INSERT INTO [Travel_Quantity]([Load_Id],[Mode_Sno],[Mode_Id],[Mode_Parent_Sno],[QA]) VALUES ( 1,'3' ,'FP' ,'2','1' )
INSERT INTO [Travel_Quantity]([Load_Id],[Mode_Sno],[Mode_Id],[Mode_Parent_Sno],[QA]) VALUES ( 1,'4' ,'SE' ,'-1','0' )
INSERT INTO [Travel_Quantity]([Load_Id],[Mode_Sno],[Mode_Id],[Mode_Parent_Sno],[QA]) VALUES ( 1,'5' ,'SP' ,'4','1' )
INSERT INTO [Travel_Quantity]([Load_Id],[Mode_Sno],[Mode_Id],[Mode_Parent_Sno],[QA]) VALUES ( 1,'6' ,'RD' ,'-1','6' )
INSERT INTO [Travel_Quantity]([Load_Id],[Mode_Sno],[Mode_Id],[Mode_Parent_Sno],[QA]) VALUES ( 1,'7' ,'BU' ,'6','3' )

========
RULE
========

1.QA of Parent Row value Greater than 0- Consider Parent and 1st Node.From the available result,

2.HasNodes = Yes, Display Parent and 1st Node

3.HasNodes = No, Display Parent Only.

================
Expected Result
================
Mode_Info|Mode_Detail|QA
AIR||4
AIR|FLIGHT|2
ROAD||6

===============
My Query
=============

learning CTE To apply for HasNodes Rules.

;with MyCTE1 as (
select
CONVERT(nvarchar(MAX),RTRIM(T2.Mode_Info)) Mode_Info, T1.Mode_Parent_Sno, T1.Mode_Sno, T1.QA ,T2.Has_Nodes
from [Travel_Quantity] T1
left join [Travel_Master] T2 on T1.Mode_Id = T2.Mode_Id
) ,
MyCTE2 as (

[code]....

View 4 Replies View Related

Recursive Query Quesiton - Table Function

Jul 20, 2005

I have a database which stores information about organisms collectedduring sediment toxicology research. For each sample, organisms insediment are collected and identified taxonomically (Order, Family,Genus, Species).Taxonomy lookup information in the database is stored in a recursivetable in the form:TSN (taxa serial number)Rank (Order, Family, Genus, Species)NameParent_TSN (related Taxa at higher taxonomic level)When the number of a particlar organism collected is entered into thedatabase, the count is stored along with the lowest level TSN theorganisms were identified to.Okay - now the problem. Depending on the type of analysis being done,a user may want organism counts at the lowest level, or rolled up to ahigher taxonomic level (usually Family). Can I write a recursivefunction which will cycle through the Taxonomy database, and providethe name of the organism at the appropriate taxonomic level? Is this areasonable approach with regard to speed and efficiency?Something Like:SELECT sample_id, 'Get Name Function(Rank, TSN)', Sum([count]) ASNoTaxa FROM dbo.tblbenthicResults could then be grouped and summed on the Name, to summarisedata for each sample/taxa.Is this a reasonable approach? Or is there a better one? Did I explainthe problem well enough?Thanks in advance,Tim

View 6 Replies View Related

SQL Server 2008 :: Small Recursive Numbers Table

Sep 20, 2015

I am trying to do a very small numbers table to compare A1c's against. However I am running into a issue when recursion hits the number 2.27 it starts to go out of my scope that I want with the next number being 2.27999999999999. Here is the code I'm using below. I need a Decimal(2,2) or Numeric (2,2) format with a range of 01.00 to 20.00. However every time I use Numeric or Decimal as the data type I get a error "Msg 240, Level 16, State 1, Line 5.Types don't match between the anchor and the recursive part in column "Number" of recursive query "NumberSequence"."

DECLARE @Start FLOAT , @End FLOAT ---DECIMAL(2,2) Numeric (2,2)
SELECT @Start=01.00, @End=20.00
;WITH NumberSequence( Number ) AS
(
SELECT @start as Number
UNION ALL
SELECT Number + 00.01
FROM NumberSequence
WHERE Number < @end

View 5 Replies View Related

Table Relationship

Apr 5, 2007

Hello, I created some SQL 2005 tables using Microsoft SQL Server Management Studio. I need to get the script code of those tables. I was able to do that by right clicking over each table. But how can I get the code for the relationships between the tables? Can't I create relationships between two tables by using T-SQL? Thanks, Miguel

View 3 Replies View Related

What Relationship To Use Between These Two Table?

Feb 7, 2008

Hi I have two tables:
1.) Operator-OperatorID{PK, int, not null}-OperatorName{varchar(100), not null}-Enabled{bit, not null}-PasswordChange{bit, not null}-BirthDate{datetime, not null}
2.) Password-PasswordID{PK, int, not null}-Password{varchar(50), not null}-ExpirationDate{datetime, not null}
I'm not sure how to design and layout these two tables. The layout of these two tables is completely flexible as the application has not been deployed. I'm open to any good suggestions.
For each Operator I want to stored up to 3 previous passwords plus their current password. The password change field is so that if the operator's password expires or gets reset, they will be forced to enter a new password. This is a simple internal company application, so password encrypting is not necessary. The ExpirationDate indicates the date that the password will expire.

Hope to hear from someone soon! Thank you!

View 3 Replies View Related

SQL Server 2008 :: Recursive CTE On Inline Table Valued Function

Jun 22, 2015

I have a recursive CTE on an inline table valued function. I need to set the MAXRECURSION option on the CTE, but SQL Server is complaining with "Incorrect syntax near the keyword 'OPTION'".

It works fine on non-inline function. I couldn't find any documentation indicating this wasn't possible.

I can use the MAXRECURSION option in call to the function

SELECT * FROM MyFunction ()
OPTION ( MAXRECURSION 0 )

but that means that the user needs to know the "MyFunction" uses recursive CTE, which defeats the purpose of the abstraction.

View 5 Replies View Related

Define More Than One Relationship Per Table?

Apr 11, 2004

Why is it not possible to define more than one relationship per table?

i have a primary table that i would like to cascade deletes to 2 other foreign tables in 2 separate relationships. why can't i do this and what are my alternatives?

thank you

View 4 Replies View Related

Relationship Inside The Same Table

Sep 19, 2005

i ve got a database that has a table...that table has a relationship between its primary key,and another field,actuelly i did it for doing menus and sub menus,so each menu has an ID say menuID and it has DEPTH and parentID which is the menuID of the parent...the problem is that i can not use "Cascade update Related Fields" or "Cascade Delete Related Records" which are really necessary ...for example when deleting parent ,not to have a child lost :)i hope i ll have an answer soon,and thanks in advancedPS: i am using MSSQL 2000 evaluation

View 4 Replies View Related

Naming Of Relationship Table

Jun 10, 2006

We have two tables. Users and Projects and there is a many-to-many relationship.Ex. A user can be assigned into multiple projects.For the relationship table, should the table name be UserProjects or ProjectUsers?Also should it be singular or plural? (ex. UsersProjects or ProjectsUsers)?

View 2 Replies View Related

Create Table With Many-to-many Relationship...

Dec 5, 2006

Hi, I come back again.
Can anyone help me to create table with many-to-many relationship. Here is my three tables
tbl_Networks
(
NID int identity(1,1) primary key,
NetworkName nvarchar(256)
)

tbl_Categories
(
CID int identity(1,1) primary key,
CateName nvarchar(256),
NID int
)

tbl_Sim
(
SID int identity(1,1) primary key,
NID int,
CID int,
NameOfSim nvarchar(256)
)
My problem is 1 value in tbl_Sim may have multiple values in table tbl_Categories and vice versal. And I don't know how to organise them


So I need some help...

View 5 Replies View Related

Table Relationship. What Am I Doing Wrong?

Feb 27, 2008

Hello,

I have 3 tables: Articles, ArticlesTags and Tags.
ArticleTags relate Articles and Tags records.

When I try to delete a record in Tags I get the following error:

The DELETE statement conflicted with the REFERENCE constraint

"FK_ArticlesTags_Tags". The conflict occurred in database "MyDB", table "dbo.ArticlesTags", column 'TagID'.
The statement has been terminated.

What am I doing wrong?

Here is how I am creating my tables:

create table dbo.Articles
(
ArticleID uniqueidentifier not null
constraint PK_Article primary key clustered,
Body nvarchar(max) not null

)
create table dbo.ArticlesTags
(
ArticleID uniqueidentifier not null,
TagID uniqueidentifier not null,
constraint PK_ArticlesTags
primary key clustered (ArticleID, TagID),
constraint FK_ArticlesTags_Articles
foreign key(ArticleID)
references dbo.Articles(ArticleID)
on delete cascade,
constraint FK_ArticlesTags_Tags
foreign key(TagID)
references dbo.Tags(TagID)
)
create table dbo.Tags
(
TagID uniqueidentifier not null
constraint PK_Tag primary key clustered,
[Name] nvarchar(200) not null
)

Basically, what I need is:

1. If an Article is deleted then:
> Delete all records for that Article in ArticlesTags
> Don't delete any Tag in Tags.

2. If an Tag is deleted then:
> Delete all records associated with it in ArticlesTags.
> Don't delete any Article in Articles.

What am I missing?

Thanks,
Miguel

View 2 Replies View Related

Table Relationship In VB Express

Dec 19, 2006

I
have 3 tables I am trying to relate for a music player. I was
following the example in the msdn however, my relationships do not seem
right. Here are tables i want to relate:

Table 1:
ArtistID
ArtistName:

Table 2:
RecordingID
RecordingName
ArtistID

Table 3:
TrackID
TrackName
TrackNumber
TrackLocation
RecordingID

So
the main idea here is that the foreign keys are recordingId and
artistID. So what i did is created the 3 tables and then make a
diagram to create the relationships. I then was reading this post:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=219696&SiteID=1

What
i want to do is use 2 different text boxes lets say and as i move from
the records in the Record_table (2) the corresponding artist will
change with it. However in the dataset the relationship looks like
this:
Artist -> Recording -> Track.... inorder for me to get
this relationship to work correctly i have to change all the
relationships in the dataset diagram. This way the dataset would look
like this: Track -> Recording ->Artist. This way i can use the
2 bindings to reference each other as stated in the link above. why
doesnt the relationship of the database know this already? why do i
have to change the relationship in the datasets.

View 3 Replies View Related

Problems Creating Second Relationship To The Same Table

Apr 6, 2007

I have two tables: ads and categories. I have an existing relationship: categories.id (PK) and ads.categoryid (FK). Now I want to create additional relationship with categories.id (PK) on ads.SecondCategoryID (FK). When I try to save it in SQL Manager I get the following error:
- Unable to create relationship 'FK_classifieds_Ads_classifieds_Categories2'.  The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_classifieds_Ads_classifieds_Categories2". The conflict occurred in database "mydb", table "dbo.classifieds_Categories", column 'Id'.
 

View 6 Replies View Related

Create A View For One-to-many Relationship Table

May 8, 2006

hi..

I would like to create a view for two tables which have a one-to-many relationship.


Code:


Table: Supplier
Supp_ID
1

Table:Supplier_category
Supp_ID,StockCategoryID
1,56
1,57
1,90



How can i create a view that has columns like below:
Supp_ID, Stock
1,[56,57,90]

Thanks in advance.

View 1 Replies View Related

Using Same Table Having Parent And Child Relationship?

Mar 23, 2014

Below is my sample data of my table named "Groups"

Code:
with Groups as (
select 1 as GroupId,'Oracle' as GroupName,0 as IdParentGroup union all
select 2 as GroupId,'Microsoft' as GroupName,0 as IdParentGroup union all
select 3 as GroupId,'IBM' as GroupName,0 as IdParentGroup union all
select 4 as GroupId,'SunMicrosystem' as GroupName,1 as IdParentGroup union all
select 5 as GroupId,'peoplesoft' as GroupName,1 as IdParentGroup union all
select 6 as GroupId,'mysql' as GroupName,1 as IdParentGroup union all
select 7 as GroupId,'Nokia' as GroupName,2 as IdParentGroup union all
select 8 as GroupId,'EShop' as GroupName,2 as IdParentGroup union all
select 9 as GroupId,'Meiosys' as GroupName,3 as IdParentGroup union all
select 10 as GroupId,'UrbanCode' as GroupName,3 as IdParentGroup )
select * from groups;

Expected result:

Code:
with ExpectedResult as (
select 'Oracle' as GroupName,'SunMicrosystem' as SubGroup union all
select '' as GroupName,'peoplesoft' as SubGroup union all
select '' as GroupName,'mysql' as SubGroup union all
select 'Microsoft' as GroupName,'Nokia' as SubGroup union all
select '' as GroupName,'EShop' as SubGroup union all
select 'IBM' as GroupName,'Meiosys' as SubGroup union all
select '' as GroupName,'UrbanCode' as SubGroup )
select * from ExpectedResult;

some sample query to how to achieve this parent-child has the same table.

View 9 Replies View Related

SQL 2012 :: Junction Table In Many To Many Relationship

May 5, 2014

Why do we need a junction table in a many to many relationship? Why can't everything be in just 2 tables?

View 9 Replies View Related

Want 1 To Many Relationship When Child Table Has No Primary Key

Jul 20, 2005

I want to create a 1-many relationship. Parent table has a primarykey, child table has no primary key. The child table does have anindex with all four fields of the parent's PK. How can I do this?Thanks, Bob C.

View 9 Replies View Related

How Can I Get Primary Key Col And Other Two Cols In The Same Table Become One To One Relationship.

Jun 12, 2006

For ex.

Table Match_List ( MatchID, UserID_A, UserID_B)

constraints like

MatchID primary key

UserID_A <> UserID_B

unqiue index (UserID_A,UserID_B)

but I wish to exclude duplicated rows like 1,1,2 & 2,2,1,

cause UserA to UserB, and UserB to UserA are the same thing.

How can I get this?

View 7 Replies View Related

Transact SQL :: How To Update Table In Many To Many Relationship

Nov 30, 2015

I am having challenge to update the redemption table from the multiple card activation table.  I want to update the redemption table with the activation date closest to the redeem date.  

For example:  Redeem date 20071223, I need to update the top row Date, Year, Period fields from the Card activation table.

Redeem date 20071228, I want to refer to the second row in the Card activation table date 20071228.  
Redeem date 20080316 or later, I want to use the last row in the card activation table date 20080316.

How to modify the update query to select the right activation row accordingly?

Below is my partial code I used but it always pick the 20071223 date to update my redemption table.

 CREATE TABLE #Card
 (
       [CardNumber] varchar(20)
 ,[ Date] int
 ,[ Year] int
 ,[ Month] int
 ,[ Period] int
  )  
 
[Code] ....

View 13 Replies View Related

Trying To Enforce Ref Integrity On Hierarchy Table Relationship

Dec 28, 2007

I've got a table that includes:CREATE TABLE [dbo].[Content] (  [Id] int IDENTITY(1, 1) NOT NULL,  [ParentId] int NULL,
I'm wanting to make sure that a ParentId must be in the table as Id someplace else.  When I try to do it by making it a foreign key  get the error:
--------------- SQL ---------------
ALTER TABLE [dbo].[Content]ADD CONSTRAINT [Content_fk3] FOREIGN KEY ([Id])   REFERENCES [dbo].[Content] ([ParentId])   ON UPDATE NO ACTION  ON DELETE NO ACTIONGO
---------- ERROR MESSAGE ----------
There are no primary or candidate keys in the referenced table 'dbo.Content' that match the referencing column list in the foreign key 'Content_fk3'.Could not create constraint. See previous errors.
 
Any ideas? 
 
ALTER TABLE [dbo].[Content]ADD CONSTRAINT [Content_fk3] FOREIGN KEY ([Id])   REFERENCES [Content].[dbo] ([ParentId])   ON UPDATE NO ACTION  ON DELETE NO ACTIONGO
 

View 3 Replies View Related







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