SQL Server sp_rename Object not found

b09cbbtk  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(93)

I am doing a refactor of a database. In this process I am renaming some of the existing tables, keys and constraints. They will be recreated on the new refactored tables. Then data will be moved to the new tables before dropping the old tables.

I have one foreign key when I try to use Exec sp_rename I get an error back the object does not exist.
If I try to use print object_id('xxx') I get nothing back.

It is a valid object and I can find it in the sys.objects table .
If I try to use print Object_Name('123456789') with the object id from the sys.objects table it returns the name I am using in the sp_rename .

Any one got an idea why the sp_rename can not find the object?

0yg35tkg

0yg35tkg1#

Use sp_rename with type:

EXEC dbo.sp_rename 
   'dbo.FK_FRP_File_DataMatrix',
   'FK_FRPFileID_FRPDataMatrixImportETL',
   'OBJECT';

Demo:

CREATE TABLE tab1 (ID INT PRIMARY KEY,
                    col1 INT NOT NULL)
CREATE TABLE tab2 (ID INT PRIMARY KEY)

ALTER TABLE tab1
ADD CONSTRAINT FK_FRP_File_DataMatrix FOREIGN KEY (col1)
REFERENCES tab2(ID);

 EXEC dbo.sp_rename 
   'dbo.FK_FRP_File_DataMatrix',
   'FK_FRPFileID_FRPDataMatrixImportETL',
   'OBJECT';

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS;

SqlFiddleDemo

zwghvu4y

zwghvu4y2#

Thanks but I get this error "Either the parameter @objname is ambiguous or the claimed @objtype (OBJECT) is wrong.". I believe the issue is some how when I created the foreign key the Schema name 'dbo.' is actually part of the name of the object. So when I exec the sp_rename it looks in Schema dbo for FK_FRP_File_DataMatrix which doesn't exist. The name really is dbo.FK_FRP_File_DataMatrix in the objects table. If I manually remove the dbo. from the name under Keys then and rename it. Need to fix this on my production database.

7d7tgy0s

7d7tgy0s3#

Drop the constraint on the old table ( Table1_Old ):

ALTER TABLE dbo.Table1_Old DROP CONSTRAINT FK_Table1_Table2
GO

Add the constraint with the new name on the old table:

ALTER TABLE dbo.Table1_Old  WITH CHECK 
ADD  CONSTRAINT FK_Table1_Table2_Old FOREIGN KEY(FileId)
REFERENCES dbo.Table2 (FileId)
GO

Now you are free to add the constraint on the new table ( Table1 ) with the old name of FK_Table1_Table2 .

ghhkc1vu

ghhkc1vu4#

I ran into this error today. To add to the currently upvoted answer, you need to include brackets around each piece of the tablename like so:

sp_rename '[dbo].[table_column]', 'newvalue'

相关问题