亲爱的,我认为解决方案非常优雅。我将其写为纯粹的答案,因为它是最接近所需解决方案的完整替代方案。但是我会将您的答案标记为答案,因为它是正确回答我最初问题的答案。
是的,所以首先我所做的是,我得到了触发器需要外键的供应商的许可,在他们的表中创建一个新列作为其他供应商表的排序规则中的持久计算列:
DECLARE @Collation nvarchar(100)
DECLARE @SQL nvarchar(1000)
SET @Collation = ( SELECT collation_name FROM sys.columns WHERE OBJECT_ID IN ( SELECT OBJECT_ID FROM sys.objects WHERE type = 'U' AND name = 'Vendor1Table' ) AND name = 'Vendor1Column' )
SET @SQL = 'ALTER TABLE [Vendor2Table] ADD [Vendor2ComputedColumn] AS [Vendor2Column] COLLATE ' + @Collation + ' PERSISTED'
EXECUTE( @SQL )
GO
接下来,我在计算列中添加了一个候选键:
ALTER TABLE [Vendor2Table] ADD CONSTRAINT [CCUNQ1_x] UNIQUE NONCLUSTERED
(
[Vendor2ComputedColumn] ASC
)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
GO
然后,我只是为计算列创建了外键:
ALTER TABLE [dbo].[Vendor1Table] WITH CHECK ADD CONSTRAINT [CCFOK01_x] FOREIGN KEY ( [Vendor1Column] )
REFERENCES [dbo].[Vendor2Table] ( [Vendor2ComputedColumn] )
GO
ALTER TABLE [dbo].[Vendor1Table] CHECK CONSTRAINT [CCFOK01_x]
GO
最后,原始的 SQL 脚本顺利通过:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE CONSTRAINT_NAME =
(
SELECT name FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID( 'Vendor1Table' )
AND referenced_object_id = OBJECT_ID( 'Vendor2Table' )
)
希望这个小演练有一天能帮助其他一些人:)
感谢大卫的帮助,不胜感激!