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

Wednesday, 7 March 2012

Confused with primary keys and foreign keys

Hi, I am currently doing a database project for my company. The database contains 5 tables inside, let's say A,B,C,D,E. The primary key of table A is referenced by all other tables. If an instance is created in other tables except in table A, it means that the foreign keys are not null. However, if an instance is created in table A, it doesn't necessarily mean that the primary key of that particular instance must be referenced by another instance in other tables. In other words, the foreign keys in other tables have null value.

Now, the question is how can I display this primary key in table A together with primary keys of other tables since some of them may not even exist yet? By displaying all the primary keys, I can therefore check that the primary keys in other tables still don't exist and with this, I can input a value to it.

P.S. I am connecting the database with VB 2005 Express Edition and I always get blank value when I tried to retrieve the value.

Thank you very much for the help

Foreign Key:

Is the advanced check constraint which will check the set of values from the another table. The another/reference table is called parent/master table & the current table is called child/detailed table. The Master table which holds the set of value should be not null unique. (you can’t have the more than one Parent for single Child). But your child table column can hold NULL value (which is not yet born)

Primary key:

Is the table levelconstraint which will ensure your table columns have a unique & not null values.

Display the Parent & child values (which is not yet born):

You have to use OUTER JOIN to achieve this. If you post more information we can provide the rite information to you.

|||

The basic problem is that IF there is not a row in the Child table (table with FK), or there is a row, but its FK value is NULL, there is no way to 'connect' the row to the Parent table (table with PK).

It is possible to 'simulate' the missing rows by using a LEFT JOIN, and referring to the Parent table first.

Try out this sample code to see how to combine tables where both tables have matching values, and also where one table is missing a FK value from the other table.

Code Snippet


--***********************************
--Problem: Demonstrate PK-FK JOINS


CREATE TABLE Parent
( RowID int IDENTITY PRIMARY KEY,
MyValue varchar(20)
)
GO


CREATE TABLE Child
( RowID int IDENTITY PRIMARY KEY,
ParentID int REFERENCES Parent(Rowid),
MyValue varchar(20)
)
GO


SET NOCOUNT ON


INSERT INTO Parent VALUES ( 'Parent1' )
INSERT INTO Parent VALUES ( 'Parent2' )
INSERT INTO Parent VALUES ( 'Parent3' )
INSERT INTO CHILD VALUES ( 2, 'Child1' )
INSERT INTO CHILD VALUES ( 3, 'Child2' )
INSERT INTO CHILD VALUES ( 2, 'Child3' )
INSERT INTO CHILD VALUES ( NULL, 'Child4' )


-- To find ONLY Parents AND their Children
SELECT
ParentID = p.RowID,
ParentValue = p.MyValue,
ChildID = c.RowID,
ChildValue = c.MyValue
FROM Parent p
JOIN Child c
ON p.RowID = c.ParentID


-- To find All Parents and Children (if Any)
SELECT
ParentID = p.RowID,
ParentValue = p.MyValue,
ChildID = c.RowID,
ChildValue = c.MyValue
FROM Parent p
LEFT JOIN Child c
ON p.RowID = c.ParentID


-- To find Parents without Children
SELECT
ParentID = p.RowID,
ParentValue = p.MyValue,
ChildID = c.RowID,
ChildValue = c.MyValue
FROM Parent p
LEFT JOIN Child c
ON p.RowID = c.ParentID
WHERE c.ParentID IS NULL


-- To find Children without Parents (Orphans)
SELECT
ParentID = p.RowID,
ParentValue = p.MyValue,
ChildID = c.RowID,
ChildValue = c.MyValue
FROM Parent p
RIGHT JOIN Child c
ON p.RowID = c.ParentID
WHERE c.ParentID IS NULL


DROP TABLE Child
DROP TABLE Parent

|||Thanks for both your suggestions, but I don't have any idea how to perform LEFT JOIN on 5 tables. Can you gimme some idea on this? Thanks..|||

Manivannan.D.Sekaran wrote:

Foreign Key:

Is the advanced check constraint which will check the set of values from the another table. The another/reference table is called parent/master table & the current table is called child/detailed table. The Master table which holds the set of value should be not null unique. (you can’t have the more than one Parent for single Child). But your child table column can hold NULL value (which is not yet born)

Primary key:

Is the table level constraint which will ensure your table columns have a unique & not null values.

Display the Parent & child values (which is not yet born):

You have to use OUTER JOIN to achieve this. If you post more information we can provide the rite information to you.

The child values are actually not null, they are only not yet born. However, I need to display both the parent table which already has a child and which has no child at all. I will try to use OUTER JOIN in the code and see how the result will be. Thanks a lot.

Saturday, 25 February 2012

confused about pivot

I need to transform the following layout by pivoting, but am confused ......I have a compound primary key that I want to keep intact but then values in the row need to be broken out into their own row.

I need to go from this...

PKcol1 PKcol2 PKcol3 col4 col5 col6 col7

A 2007 1 Y N N N

A 2007 2 Y Y N N

A 2007 3 N N N Y

into this....

A 2007 1 col4 Y

A 2007 1 col5 N

A 2007 1 col6 N

A 2007 1 col7 N

A 2007 2 col4 Y

A 2007 2 col5 Y

A 2007 2 col6 N

A 2007 2 col7 N

A 2007 3 col4 N

A 2007 3 col5 N

A 2007 3 col6 N

A 2007 3 col7 Y

Can I do this using PIVOT or should I just do 4 inserts (one for each col40col7) into a temp table? Any suggestions?

Give a look to UNPIVOT in books online; this is an UNPIVOT and not a PIVOT

|||

Kent is right, you need to use UNPIVOT.

select

PKcol1,

PKcol2,

PKcol3,

col,

[value]

from

dbo.t1

unpivot

(

[value]

for col in ([col4], [col5], [col6], [col7])

) as unpvt;

AMB

Friday, 24 February 2012

Conflict 'missing key', but the key is there !

Hello,
I use a merge replication and I can see many conflicts (in differents tables) having the same source error. The error message in Conflict viewer says:
The row was inserted at 'Publisher.DataBase' but could not be inserted at 'Subscriber.DataBase'. INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK_Table1_Table2'. The conflict occurred in database 'DataBase', table 'Table2', column 'ColKe
y'.
But I can see on Subscriber.DataBase, on Table2 that I have the row with the key that was reported as /missing' !!!
What this could means?
Does it means that SQL try to insert the new lines first in Table1 and after this insert in Table2? Is that possible if I have defined a relation between the 2 tables ?
Thanks in advance
Catalin,
firstly let me confirm:
are the two tables are articles in the same publication
have the PK and the FK been added at the publisher before synchrionization
after synchronization does the PK value make it to the subscriber (assuming
above is true)
Really the order should be OK, although there are known issues if you have
made a lot of changes
(http://support.microsoft.com/default.aspx?scid=kb;[LN];307356). The
recommended solution in the article is to increase
the -UploadGenerationsPerBatch parameter.
Regards,
Paul Ibison

Conflict Error

Hi All;

I am getting ;

INSERT statement conflicted with TABLE FOREIGN KEY constraint 'FK_ChecklistCases_ChecklistFGroups'. The conflict occurred in database 'Test', table 'ChecklistFGroups'. The statement has been terminated.

but it seems to be no error can you help me please I can send you the related part of database

thank youit says you are violating the forien key constriant..its always a good idea to check if the data exists before you insert..

hth

conflict between (cascade) DELETE Trigger and Foreign Key Constrain

I'm trying to create relational database with some triggers in SQL Server 7.0, but it doesn't work as expected. Let's say that I have 'Office' database with two tables, 'Users' and 'UserRights' (userRights table should have much more rights, but that's not relevant for this problem):

CREATE TABLE [Users] (
[FS_Username] [nvarchar] (8) NOT NULL ,
[FS_Password] [nvarchar] (32) NOT NULL ,
CONSTRAINT [PK_Users] PRIMARY KEY NONCLUSTERED
(
[FS_Username]
) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [UserRights] (
[FS_Username] [nvarchar] (8) NOT NULL ,
[FI_UserType] [int] NOT NULL CONSTRAINT [DF_UserRights_FI_UserType] DEFAULT (1),
[FI_AllowLogin] [int] NOT NULL CONSTRAINT [DF_UserRights_FI_AllowLogin] DEFAULT (1),
CONSTRAINT [PK_UserRights] PRIMARY KEY NONCLUSTERED
(
[FS_Username]
) ON [PRIMARY] ,
CONSTRAINT [FK_UserRights_Users] FOREIGN KEY
(
[FS_Username]
) REFERENCES [Users] (
[FS_Username]
)
) ON [PRIMARY]
GO

Foreign Key CONSTRAIN above is created by adding both tables to the diagram and defining relationship between these two tables FS_Username field, where 'Enable relationship for INSERT and UPDATE' option is turned ON. You can easily see this if you create diagram youself and insert these two tables in it.
Next to this, I created two triggers that should handle inserting/deleting rows in UserRights table as consequence of inserting/deleting rows in Users table:

CREATE TRIGGER InsertUserRights ON Users
FOR INSERT
AS
BEGIN
INSERT INTO UserRights (FS_Username) (SELECT FS_Username FROM Inserted)
END

CREATE TRIGGER DeleteUserRights ON Users
FOR DELETE
AS
BEGIN
DELETE UserRights WHERE FS_Username IN
(SELECT FS_Username FROM Users)
END

Now, when (manually) I insert row in Users table, UserRights table gets updated accordingly. HOWEVER, when I try to delete one or more entries from Users table, I get error report. For example, if you try to execute following two commands:

Insert Into Users (FS_Username, FS_Password) VALUES ('John', 's')

Delete from Users

... first command will succede, but second one will fail with message:

DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_UserRights_Users'. The conflict occurred in database 'Office', table 'UserRights', column 'FS_Username'.
The statement has been terminated.

Does anyone know how to resolve this problem without loosing constrains and triggers ? (If I turn off 'Enable relationship for INSERT and UPDATE' option for relationship, things will work fine, but than I can make inconsistent data in UserRights table).

tnx a lot,
DejanSorry, second trigger should be:

CREATE TRIGGER DeleteUserRights ON Users
FOR DELETE
AS
BEGIN
DELETE UserRights WHERE FS_Username IN
(SELECT FS_Username FROM deleted)
END

This is just the correct trigger, it doesn't solve the problem in hand...

Dejan

Friday, 10 February 2012

CONFIGURE REPORT SERVER - Initialization button disabled / Key not valid for use in specified st

Hi There,

I am trying to setup a RS with Configure Report Server tool. (Windows 2003 Server / SQL 2005)

    * All the items are with green check points except Encryption Keys (Blue exclamation point) and initialization wich is disabled. * Event log shows a lots of errors: Report Server Windows Service (SQL2K5) cannot connect to the report server database. * Browsing the Web Reports Server is returning the errror: Key not valid for use in specified state. (Exception from HRESULT: 0x8009000B)

Can someone give me a ideea where to dig next?

Regards,

Toronto,

Canada

Which edition of RS are you using? The initialization button could be disabled because your edition doesn't support scale-out deployment. Does the disabled button show a check mark or a cross?

When you browse http://<server>/reportserver, are there any errors in the log file? Also review what's on the database setup panel. Perhaps try to reapply the settings on the panel. (The cannot connect to report server database error is suspicious considering the database setup panel shows green check mark.)

|||

EDITION:

Microsoft SQL Server 2005 - 9.00.2047.00 (Intel X86) Apr 14 2006 01:12:25 Copyright (c) 1988-2005 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 1)

Initialization button show a cross.

(The cannot connect to report server database error is suspicious considering the database setup panel shows green check mark.) - I totaly agree with you here - this is a paradox.

The database button is green with the check sign and the log is full of:

Report Server Windows Service (SQL2K5) cannot connect to the report server database.

Encryption Keys is blue with exclamation sign. Buttons backup and change disabled, delete and restore available.

Is there any way to post some screenshots of these?

Regards,

Toronto

|||

Scale-out is only supported for Developer, Enterprise and Evaluation edition, so you'd expect the Initialization to be disabled. (However, it should not be a cross.)

The database button is green means that the connection information is set in rsreportserver.config file. It is possible that the connection information is incorrect. Although, if you used the config tool to configure this panel, you should end up with a good connection information. Perhaps you can review http://msdn2.microsoft.com/en-us/ms159133.aspx. After reapplying the settings, check if your RS catalog databases is granted the correct permissions. Perhaps you can also check from the SQL profiler if your database is getting hit, and if the logons are denied.

|||

RS service is running under the same Windows account wich is designated for SQL server service. This account is part of Administrators group on OS and on SQL instance.

Does RS service require a distinct account?

I have loged in the server with the Windows account above mentioned.

I have accesse the RS database and the RSTemp database with no problem.

What else is missing?