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