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.
Related
I have two datasets:
one is data about dogs [my data]
the second is a lookup table of matching keys [I have no control over this data]
The matching keys are updated regularly, and I want to create a View (or something that fulfills the same purpose) of the Dog dataset, which always joins on the most recent matching keys. Furthermore, I need to be able to reference it inline - as though it was a table.
The match updates in the lookup table are differentiated by their schema names, so to get the most recent, I just have to identify the latest schema name and swap it out of the query.
Given that both Views and Table Valued Functions prohibit dynamic SQL, and Stored Procedures can't be referenced like a table can be how can I achieve this in just SQL?
The match updates in the lookup table are differentiated by their schema names, so to get the most recent, I just have to identify the latest schema name and swap it out of the query.
You can use a view to solve this problem, but you need some way of altering it whenever new data is entered into the database.
I'm assuming that whenever a new schema is created, a new table is also created in that schema, but the table name and it's column names are always the same. Note that this assumption is critical to the solution I'm about to propose - and that solution is to use a DDL trigger listening to the create_table event on the database level to alter your view so that it will reference the schema of the newly created table.
Another assumption I'm making is that you either already have the initial view, or that you are working with SQL Server 2016 or higher (that allows create or alter syntax).
So first, let's create the initial view:
CREATE VIEW dbo.TheView
AS
SELECT NULL As Test
GO
Then, I've added the DML trigger, which creates and executes a dynamic alter view statement based on the schema of the newly created table:
CREATE TRIGGER AlterViewWhenSchemaChanges
ON DATABASE
FOR CREATE_TABLE
AS
DECLARE #Sql nvarchar(max),
#NewTableName sysname,
#NewSchemaName sysname;
SELECT #NewSchemaName = EVENTDATA().value('(/EVENT_INSTANCE/SchemaName)[1]', 'NVARCHAR(255)'),
#NewTableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]', 'NVARCHAR(255)');
-- We only want to alter the view when this specific table is created!
IF #NewTableName = 'TableName'
BEGIN
SELECT #Sql =
'ALTER VIEW dbo.TheView
AS
SELECT Col as test
FROM '+ #NewSchemaName +'.'+ #NewTableName
EXEC(#Sql)
END
GO
This way, whenever a new table with the specific name (TableName in my example) is created, the view gets altered to reference the last TableName created (which is obviously created in the newest schema).
Testing the script:
SELECT * FROM dbo.TheView;
GO
Results:
Test
NULL
Create a new schema with the table TableName
CREATE SCHEMA SchemaName
CREATE TABLE SchemaName.TableName (Col int);
GO
-- insert some data
INSERT INTO SchemaName.TableName(Col) VALUES (123);
-- get the data from the altered view
SELECT * FROM dbo.TheView
Results:
test
123
You can see a live demo on Rextester.
In my Stored procedure, I have added a command to create a hash temp table #DIR_CAT. But every time I execute the procedure I get this error:
"There is already an object named '#DIR_Cat' in the database."
Even when I have already created an Exists clause at the start of SP to check and drop the table if it is present. Any help is much appreciated.
The code goes like this.
if exists (select * from dbo.sysobjects where id = object_id(N'#DIR_Cat') )
drop table #DIR_Cat
/* some lines of code*/
CREATE TABLE #DIR_Cat (XMLDta xml)
/* some lines of code*/
INSERT #DIR_Cat exec (#stmt)
/* some lines of code*/
drop table #DIR_Cat
Main issue is you're not fully qualifying your objects. Your temp table lives in tempdb, whereas the system views use whatever database you're currently connected to by default. So essentially you're looking for the temp table, but you're looking in whatever database your currently connected to (which I'm guessing is not tempdb).
I'm assuming you're using SQL Server here, although you did also mention mysql in the tags. If that's what you're using, this code may not apply.
Here's the snippet I use for temp table drop/create
if object_id('tempdb.dbo.#<TableName, sysname, >') is not null drop table #<TableName, sysname, >
create table #<TableName, sysname, >
(
)
Side note, don't use dbo.sysobjects. That's a really old compatibility view. If you want to use objects, use sys.objects instead.
temp table does not exists in local DB sys.objects, it is in tempdb
you need to query tempb.sys.objects
the name of the temp table does not appear exactly as it is in the tempdb.sys.objects.
You can't query it just like
select *
from tempdb.sys.objects
where name = '#DIR_Cat' -- This does not works
you need to use object_id()
select *
from tempdb.sys.objects
where object_id = object_id('tempdb..#DIR_Cat')
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
Someone already had asked this question here but didn't get an answer for that question .
How can I change a table in SQL Server 2012 that starts with a dbo prefix to one without ?
Here is the answer (alter !!!) , for anyone that might need it someday :
IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'MyDbo'))
BEGIN
EXEC ('CREATE SCHEMA [MyDbo] AUTHORIZATION [dbo]')
END
ALTER SCHEMA MyDbo
TRANSFER dbo.your_old_table
GO
change > mydb.tableName to dbo.tableName
1 .Click F4 or ( view > Properties window) ,
2 .then click on your Table.
3 .in properties window , in schema field , change the attribute.
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];