If I have a table with a combined PK, can I somehow create
a FK to one of the PK?
Example:
Table Client
-------
PK ClientId
PK Version
Table Product
-------
PK ProductId
FK ClientId - Is this possible?! I cant make it work, becaust it says
that ClientId in table Client must be uniqe. But I just want to know that
the ClientId entered in Product is valid and exists in Client.
Please help me!
/EClient
------
ID
Client_ID
Version
Primary Key (ID);
UNIQUE (Client_id, Version);
Products
------
Product_id
Client_ID
Primary Key (Product_ID);
foreign key (client_ID) references Client(ID);|||Use Pubs
go
CREATE TABLE [Client] (
[ClientId] [int] NOT NULL ,
[Version] [int] NOT NULL ,
CONSTRAINT [PK_Client] PRIMARY KEY CLUSTERED
(
[ClientId],
[Version]
) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER FUNCTION [udf_ClientIdCheck] (@.ClientId int)
RETURNS INT
AS
BEGIN
DECLARE @.return_value bit
if exists (select * from Client where ClientId = @.ClientId)
set @.return_value = 1
else
set @.return_value = 0
return @.return_value
END
go
CREATE TABLE [Product] (
[Productid] [int] NULL ,
[Clientid] [int] check (dbo.udf_ClientIdCheck(ClientID) =1)
) ON [PRIMARY]
GO
insert into client values(1,1)
insert into product values (1,1)
insert into product values (1,2)
go
select * from product
go
drop table [Client]
drop table [Product]
go
You will need to make a UDF to use in a check constraint|||Wow!
Thats perfect! Works fine!
Thank you very much.
/E
Originally posted by Enigma
Use Pubs
go
CREATE TABLE [Client] (
[ClientId] [int] NOT NULL ,
[Version] [int] NOT NULL ,
CONSTRAINT [PK_Client] PRIMARY KEY CLUSTERED
(
[ClientId],
[Version]
) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER FUNCTION [udf_ClientIdCheck] (@.ClientId int)
RETURNS INT
AS
BEGIN
DECLARE @.return_value bit
if exists (select * from Client where ClientId = @.ClientId)
set @.return_value = 1
else
set @.return_value = 0
return @.return_value
END
go
CREATE TABLE [Product] (
[Productid] [int] NULL ,
[Clientid] [int] check (dbo.udf_ClientIdCheck(ClientID) =1)
) ON [PRIMARY]
GO
insert into client values(1,1)
insert into product values (1,1)
insert into product values (1,2)
go
select * from product
go
drop table [Client]
drop table [Product]
go
You will need to make a UDF to use in a check constraint
Showing posts with label versiontable. Show all posts
Showing posts with label versiontable. Show all posts
Tuesday, March 20, 2012
Problem with FK
Labels:
client--pk,
clientidpk,
combined,
createa,
database,
microsoft,
mysql,
oracle,
pkexampletable,
server,
somehow,
sql,
table,
versiontable
Subscribe to:
Posts (Atom)