简体   繁体   中英

SQL Server Management Studio does NOT let me create multiple foreign keys to multiple primary keys

I have a table ApplicationRegion in a one-to-many relationship to Translation .

I want to set FK's from Translation.appname/isocode to ApplicationRegion.appname/isocode

But that did not work as you can see from the screenshot.

When the FK configure window opens 3 columns are shown on the left/right side

appname
isocode
resourcekey

Then I chose as parent table ApplicationRegion and removed the resource key column from the FK setting.

And clicked OK but then I got the error you see on the screenshot.

在此处输入图片说明

Finally I made it work with that workaround and I would like to know why I had to use this workaround?

  1. Remove PK from Translation.ResourceKey column
  2. Open FK configure window
  3. Only 2 columns appear now as foreign keys
  4. I click OK
  5. Now I add the PK again to Translation.ResouceKey column
  6. I added test data to all 3 tables and everything is fine.

WHY this workaround?

UPDATE

HAHA...

在此处输入图片说明

I think you must have hit a weird glitch in SSMS. I was able to create your schema using SSMS 2014 without any errors. It did pre-fill the three composite primary key columns when adding the new FK. I was careful to make sure they were all blanked out before I started to add the two columns in the FK. Maybe SSMS thought one of the blank rows still had data in it.

Edit: Just had one more thought, SSMS is know for caching any changes that are made when editing a table. For example, if you go to modify two tables and have both edit windows open. Then you change the PK in one window and then try to reference it in the second window, it will error because it has cached what the schema was for the first table when the window was first opened.

Here is my generated DDL:

CREATE TABLE [dbo].[AppRegion](
    [appname] [nvarchar](50) NOT NULL,
    [isocode] [char](5) NOT NULL,
 CONSTRAINT [PK_AppRegion] PRIMARY KEY CLUSTERED 
(
    [appname] ASC,
    [isocode] ASC
)
) ON [PRIMARY]

CREATE TABLE [dbo].[Translation](
    [ResourceKey] [nvarchar](128) NOT NULL,
    [appname] [nvarchar](50) NOT NULL,
    [isocode] [char](5) NOT NULL,
    [text] [nvarchar](400) NULL,
 CONSTRAINT [PK_Translation] PRIMARY KEY CLUSTERED 
(
    [ResourceKey] ASC,
    [appname] ASC,
    [isocode] ASC
)
) ON [PRIMARY]

ALTER TABLE [dbo].[Translation]   ADD  CONSTRAINT [FK_Translation_AppRegion] FOREIGN KEY([appname], [isocode])
REFERENCES [dbo].[AppRegion] ([appname], [isocode])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM