SQL Server 2005 - SQL 语句根据表名查询从表中删除聚集键?

发布于 2024-07-30 14:27:57 字数 238 浏览 7 评论 0原文

我正在尝试恢复 Microsoft Dynamics NAV 数据库的备份,不幸的是,它失败了,因为它尝试为已经具有聚集键的表设置聚集键。

在 NAV 中,数据库中的每个公司都会获得自己的表副本,并以公司名称为前缀,例如 COMPANY$User_Setup。 因此,我想删除给定公司上的任何聚集键,这意味着名称以“Company$”开头的任何表上。

有人有可以执行此操作的 SQL 语句吗?

I am trying to restore a backup of a Microsoft Dynamics NAV database, which unfortunately fails as it tries to set a CLUSTERED KEY for the tables which already have clustered keys.

In NAV, every company in the database gets its own copy of the tables, prefixed with the Company's name, e.g. COMPANY$User_Setup. I'd therefore like to remove any clustered key on a given company, which means on any table which name starts with 'Company$'.

Has anybody got a SQL statement that could perform this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

给妤﹃绝世温柔 2024-08-06 14:27:57

您需要将其作为光标来执行。 假设每个 PK 约束的命名一致并且基于表名,您可以执行类似的操作(未经测试,因此可能包含拼写错误或 vauge 语法错误):

DECLARE mycursor CURSOR FOR SELECT name FROM sysobjects WHERE name LIKE 'Company$%'

OPEN CURSOR
FETCH NEXT FROM mycursor INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = N'ALTER TABLE QUOTENAME(' + @tablename + ') DROP CONSTRAINT PK_' + @tablename 
    EXEC sp_ExecuteSQL @sql
    FETCH NEXT FROM mycursor INTO @tablename
END

CLOSE CURSOR
DEALLOCATE CURSOR

如果您的 PK 不是根据表名命名的,那么您必须修改它才能基于 sysconstraints 或 sysindexes 进行查询以获得实际的 PK 名称。

You'll need to do it as a cursor. Assuming each PK constraint is named consistantly and is based on the table name, you'd be able to do something like (untested, so may contain typos or vauge syntax errors):

DECLARE mycursor CURSOR FOR SELECT name FROM sysobjects WHERE name LIKE 'Company$%'

OPEN CURSOR
FETCH NEXT FROM mycursor INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = N'ALTER TABLE QUOTENAME(' + @tablename + ') DROP CONSTRAINT PK_' + @tablename 
    EXEC sp_ExecuteSQL @sql
    FETCH NEXT FROM mycursor INTO @tablename
END

CLOSE CURSOR
DEALLOCATE CURSOR

If your PK's aren't named based on tablename, then you'll have to modify this to also query based on sysconstraints or sysindexes to get the actual PK name.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文