Change Schema Name Of Table In SQL - sql

I want to change schema name of table Employees in Database. In the current table Employees database schema name is dbo I want to change it to exe. How can I do it ?
Example:
FROM
dbo.Employees
TO
exe.Employees
I tried with this query:
ALTER SCHEMA exe TRANSFER dbo.Employees
But this gives me an error:
Cannot alter the schema 'exe', because it does not exist or you do not
have permission.
What did I miss?

Create Schema :
IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe'))
BEGIN
EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
END
ALTER Schema :
ALTER SCHEMA exe
TRANSFER dbo.Employees

ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
I always have to use the brackets when I use the ALTER SCHEMA query in SQL, or I get an error message.

Try below
declare #sql varchar(8000), #table varchar(1000), #oldschema varchar(1000), #newschema varchar(1000)
set #oldschema = 'dbo'
set #newschema = 'exe'
while exists(select * from sys.tables where schema_name(schema_id) = #oldschema)
begin
select #table = name from sys.tables
where object_id in(select min(object_id) from sys.tables where schema_name(schema_id) = #oldschema)
set #sql = 'alter schema ' + #newschema + ' transfer ' + #oldschema + '.' + #table
exec(#sql)
end

CREATE SCHEMA exe AUTHORIZATION [dbo]
GO
ALTER SCHEMA exe
TRANSFER dbo.Employees
GO

Through SSMS, I created a new schema by:
Clicking the Security folder in the Object Explorer within my server,
right clicked Schemas
Selected "New Schema..."
Named my new schema (exe in your case)
Hit OK
I found this post to change the schema, but was also getting the same permissions error when trying to change to the new schema. I have several databases listed in my SSMS, so I just tried specifying the database and it worked:
USE (yourservername)
ALTER SCHEMA exe TRANSFER dbo.Employees

Your Code is:
FROM
dbo.Employees
TO
exe.Employees
I tried with this query.
ALTER SCHEMA exe TRANSFER dbo.Employees
Just write create schema exe and execute it

Check out MSDN...
CREATE SCHEMA: http://msdn.microsoft.com/en-us/library/ms189462.aspx
Then
ALTER SCHEMA: http://msdn.microsoft.com/en-us/library/ms173423.aspx
Or you can check it on on SO...
How do I move a table into a schema in T-SQL

Make sure you're in the right database context in SSMS. Got the same error as you, but I knew the schema already existed. Didn't realize I was in 'MASTER' context. ALTER worked after I changed context to my database.

In case, someone looking for lower version -
For SQL Server 2000:
sp_changeobjectowner #objname = 'dbo.Employess' , #newowner ='exe'

Be very very careful renaming objects in sql. You can cause dependencies to fail if you are not fully away with what you are doing. Having said that this works easily(too much so) for renaming things provided you have access proper on the environment:
exec sp_rename 'Nameofobject', 'ReNameofobject'

also you can transfer your data from default schema 'dbo' to your schema
from wizard by
1-double click on db diagram
2- right click on your certian entity --> select properties
3- on right at identity , change the schema name

For SQL2019:
ALTER SCHEMA [SCEMAYOUWANTTOTRANSFERTO] TRANSFER [CURRENTSCHEMA].[TABLENAME];
Example:
ALTER SCHEMA [dbo] TRANSFER [Curated].[MyTable];

Related

SQL Error - Cannot find the object "TABLE" because it does not exist or you do not have permissions

I've been banging my head against the wall for a week trying to figure this out. I have a script that is run during a database upgrade. I want to alter a column, "Test1", and add a column, "Test2" to a database table and when I run the script from the installer, I receive the above error. I run the script in SQL Server Management Studio and it works fine. Any help would be appreciated. Thanks.
IF (SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TESTTABLE' AND COLUMN_NAME = 'Test1') <> -1
BEGIN
ALTER TABLE TESTTABLE ALTER COLUMN Test1 VARCHAR(MAX)
END
IF NOT EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TESTTABLE' AND COLUMN_NAME = 'Test2')
BEGIN
ALTER TABLE TESTTABLE ADD Test2 VARCHAR(MAX)
END
It turned out that we are using ODBC connections to make the connection to the database, and it was not allowing (permitting, not sure) the script to change to another database by utilizing the "Use" statement within the script. I ended up creating a second connection to the appropriate database, and it worked and made the updates to the table. Thanks!

SQL Server - Check column if exists >> rename and change type

SQL Server:
Check column if exists when
If True : (Change/Modify) column_name and dataType
If False : Create
Schema name : Setup
Code:
IF EXISTS (SELECT 1 FROM sys.columns
WHERE Name = N'bitIntialBalance'
AND Object_ID = Object_ID(N'Setup.LeaveVacationsSubType'))
BEGIN
ALTER TABLE [Setup].[LeaveVacationsSubType]
ALTER COLUMN intIntialBalance INT NULL;
EXEC sp_RENAME 'Setup.LeaveVacationsSubType.bitIntialBalance', 'intIntialBalance', 'COLUMN';
--ALTER TABLE [Setup].[LeaveVacationsSubType] MODIFY [intIntialBalance] INT; not working
END
GO
IF NOT EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'intIntialBalance'
AND Object_ID = Object_ID(N'Setup.LeaveVacationsSubType'))
BEGIN
ALTER TABLE [Setup].[LeaveVacationsSubType]
ADD intIntialBalance INT NULL;
END
GO
If I guess correctly, the problem is that query plan is made for the whole script, and SQL Server also checks that it can actually perform all the operations, even if it is inside an if statement. That's why you'll get an error, even if in the reality that statement would never be executed.
One way to get around this issue is to make all those statements dynamic, something like this:
execute ('ALTER TABLE [Setup].[LeaveVacationsSubType] MODIFY [intIntialBalance] INT')

How to redirect a request for DB1 to DB2

Suppose I have two databases named DB1 and DB2. In DB1, there is a table named Student, In DB2, there is a stored procedure named SP1. In SP1, I am selecting data of Student Table using below query :
Select *from DB1.dbo.Student.
I have more than 300 stored procedures having above said cross database communication. Now, I want to change my database from DB1 to DB3 that is identical to DB1 from data and schema perspective.
For this, I also have to modify all 300 stored procedures that are having fully-qualified database name. Now, the query will likely to be as follows :
Select *from DB3.dbo.Student
I don't want to change all stored procedure to point DB3 now, also don't want to change my queries written in stored procedure into dynamic SQL (I know this can be done by creating dynamic SQL).
Is it possible if We run DB1.dbo.Student, It will redirect to DB3.dbo.Student. Any intermediate layer or any SQL setting.
It'll be very big help for me. Thanks In Advance !!
If the purpose of your database renaming is to migrate a database, then why not rename the databases themselves?
e.g. say rename DB1 to DB1_old and then rename DB3 to DB1
I would simply script out all stored procedures using SQL Server script generator tool. Then do a find replace on the script and find text ‘DB1.dbo.’ and replace with ‘DB3.dbo.’
In the future you might want to consider using synonyms to reference external tables then you would only have to update the synonyms instead of all of your procedures. Please see following MSDN article on synonyms:
https://msdn.microsoft.com/en-us/library/ms187552.aspx
Example use of synonym:
USE [DB1]
GO
-- Create a synonym for table A located in DB2.
CREATE SYNONYM [dbo].[External_TableA] FOR [DB2].[dbo].[TableA]
GO
-- Synonym is pointing to TableA in DB2 , select statement will return data from DB2 tabla A.
SELECT *
FROM [External_TableA]
GO
-- Point the Synonym to same table but on DB3
DROP SYNONYM [dbo].[External_TableA]
CREATE SYNONYM [dbo].[External_TableA] FOR [DB3].[dbo].[TableA]
GO
-- No update was needed on views or stored procedure.
-- Synonym is pointing to TableA in DB3 , select statement will return data from DB3 tabla A.
SELECT *
FROM [External_TableA]
The follow query will generate the required DROP and CREATE script to remap your synonyms from the old database to the new database.
DECLARE #oldDB NVARCHAR(100) = 'DB2';
DECLARE #newDB NVARCHAR(100) = 'DB3';
SELECT 'DROP SYNONYM [dbo].[' + name + ']' AS [Drop Script]
,'CREATE SYNONYM [dbo].[' + name + '] FOR ' + REPLACE(base_object_name, #oldDB, #newDB) AS CreateScript
FROM sys.synonyms
ORDER BY name
its better to use USE Keyword
use [database name you want to access]
Queries and stored procedure you want to use
GO
eg
use [db1]
select *from yourTableName
exec yourStoredProcedure parm1,parm2,....
Go

To Create a Table in AdventureWorks in existing Schema

I want to create Employee2 table in adventureworks database. However when I create a table using graphic interface and save it then it has the prefix dbo and saved as dbo.Employee2.
I wish to save the table in HumanResources schema as it will be saved as HumanResources.Employee2.
How to do this?!!
IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'HumanResources '))
BEGIN
EXEC ('CREATE SCHEMA [HumanResources] AUTHORIZATION [dbo]')
END
ALTER SCHEMA HumanResources
TRANSFER dbo.Employee2
Try to understand you want to create a Table Employee2 in a defined schema HumanResources of adventureworks sample Db.
So going with GUI Go to New Table then define your Employee2 columns and datatypes etc then on Properties windows at right side of screen choose your schema HumanResources and save it. Thats it.

Add Identity column to all the tables in database Sql server 2005

I have a database that is used to transfer data across the main production database when we import data from a third party.
I would like to add an Identity column to each table.
I know that the below SQL will do for a single table, how can I do it for all the tables in the database?
ALTER TABLE dbo.YourTable
ADD Id INT IDENTITY(1,1) NOT NULL
Many thanks
You'll have to do it one table at a time - there's no "magic" way to do it to all tables at once.
You can have SQL Server generate the T-SQL statements needed for that operation by inspecting the sys.tables catalog view - assuming you want to call that identity column Id for all tables:
SELECT
t.NAME,
'ALTER TABLE [' + SCHEMA_NAME(t.SCHEMA_ID) + '].[' + t.NAME +
'] ADD Id INT IDENTITY(1,1) NOT NULL'
FROM
sys.tables t
Now, copy & paste the resulting lines of this statement and execute those lines against your database - and you're done!
U can use 'sp_MSforeachtable 'And add to Every table in your Database
just run this query:
EXEC sp_MSforeachtable '
if not exists (select * from sys.columns
where object_id = object_id(''?'')
and name = ''ColName'')
begin
ALTER TABLE ? ADD ColName <DataType> NULL ; // or NOT NULL DEFAULT
<DefaultValue>;
end';
If you are using an Azure SQL,This Stored Procedure is not available under programmability.
Either you can port it from your master database from your on-prem sql server.Or use this link to the run the stored procedure
https://gist.github.com/metaskills/893599