Cursor Changing Schema Name in SQL Server

Hello everyone,

In this article, I will provide information on how to write a cursor that changes the schema name in SQL Server.

While researching in SQL Server I was wondering how to change all schema names in one go. You can see the sample code for this below.

Just do not start this process without creating the schema you want to modify before doing this, or you will get an error. I will explain the operations here on the Northwind database. You can also work on this database to learn. Make sure you fully understand the process before attempting it on a live database.

DECLARE @currentSchemaName NVARCHAR(200),
        @tableName NVARCHAR(200);
DECLARE tableCursor CURSOR FAST_FORWARD FOR
SELECT TABLE_SCHEMA,
       TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY 1,
         2;
DECLARE @SQL NVARCHAR(400);
OPEN tableCursor;
FETCH NEXT FROM tableCursor
INTO @currentSchemaName,
     @tableName;
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQL = N'ALTER SCHEMA YeniSema TRANSFER ' + @currentSchemaName + N'.[' + @tableName + N']';
    PRINT @SQL; --You can also see the SQL Query in this section.
    EXEC (@SQL);
    FETCH NEXT FROM tableCursor
    INTO @currentSchemaName,
         @tableName;
END;
CLOSE tableCursor;
DEALLOCATE tableCursor;

The part I call NewSema is the name of the schema I created. If you have created a schema before, you can write your schema name here.

Let’s look at the table names when you run the code.

Cursor Changing Schema Name in SQL Server

As you can see, schema names from dbo have been changed to YeniSema.

Good luck to everyone in business and life.

55 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!