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

半腔热情 提交于 2019-12-11 08:34:13

问题


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...


回答1:


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])


来源:https://stackoverflow.com/questions/32748451/sql-server-management-studio-does-not-let-me-create-multiple-foreign-keys-to-mul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!