在 SQL Server 2005 中动态查找主键约束
我有以下 SQL:
ALTER TABLE dbo.PS_userVariables DROP CONSTRAINT PK_PS_userVariables;
ALTER TABLE dbo.PS_userVariables ADD PRIMARY KEY (varnumber, subjectID, userID, datasetID, listid, userVarTitle);
由于我有多个环境,因此 PK_PS_userVariables 约束名称在不同的数据库上是不同的。如何编写一个获取该名称然后将其添加到我的脚本中的脚本?
I have the following SQL:
ALTER TABLE dbo.PS_userVariables DROP CONSTRAINT PK_PS_userVariables;
ALTER TABLE dbo.PS_userVariables ADD PRIMARY KEY (varnumber, subjectID, userID, datasetID, listid, userVarTitle);
Since I have multiple environments, that PK_PS_userVariables constraint name is different on my different databases. How do I write a script that gets that name then adds it into my script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然典型的最佳实践是始终显式命名约束,但您可以从目录视图动态获取它们:
While the typical best practice is to always explicitly name your constraints, you can get them dynamically from the catalog views:
参考:Pinal Dave @ http://blog.sqlauthority.com/2008/09/06/sql-server-find-primary-key-using-sql-server-management-studio/
Ref: Pinal Dave @ http://blog.sqlauthority.com/2008/09/06/sql-server-find-primary-key-using-sql-server-management-studio/
我的用例是更新 Entity Framework 6 生成的主键约束名称,以匹配 Entity Framework Core 的主键命名约定。
由于 EF 使用迁移,我创建了
Up
和Down
迁移脚本,并创建了一个临时的长期表来存储新旧约束名称,以便我可以滚动如果需要的话回来。这是我用来更新主键约束名称的 SQL:
运行此脚本后,应使用旧的和新的约束名称填充 dbo.__OldPrimaryKeyConstraintNames。
这允许我们在出于任何原因需要时恢复重命名。
这是我用来恢复主键约束名称的 SQL:
My use case was updating primary key constraint names generated by Entity Framework 6 to match the primary key naming convention of Entity Framework Core.
As EF uses migrations, I created both an
Up
andDown
migration script, and created a temporary long-lived table to store the old and new constraint names so that I could roll back if needed.This is the SQL I used to update the primary key constraint names:
After running this script,
dbo.__OldPrimaryKeyConstraintNames
should be populated with the old and new constraint names.This allows us to revert the renaming if required for whatever reason.
This is the SQL I used to revert the primary key constraint names: