Can I change a SQL Server table name in a way that is backwards compatible? E.g add a permanent alias? - sql

I have a Sql Server 2008 database I inherited. A number of apps and SSIS packages work off that database. Not too long ago the scope of the database changed and a lot of new tables were added. As a result of this a lot of the table names (and even the database name itself) no longer make sense, resulting in a very confusing schema.
I could rename the tables straight away and change the apps and processes to use the new names but the chaos and downtime it would cause in the meantime would not be acceptable.
Is there a way I can add an alternate name for a table (like a permanent alias) that I could use to refer to either the new or old table name until all of my refactoring is complete?

Create a synonym first.
CREATE SYNONYM dbo.SensibleName FOR dbo.CrazyName;
Now find all the references to CrazyName in your codebase, and update them to reference SensibleName instead. Once you believe you have found them all, you can eventually run:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
DROP SYNONYM dbo.SensibleName;
EXEC sp_rename N'dbo.CrazyName', N'SensibleName', N'OBJECT';
COMMIT TRANSACTION;
If you need to make column names more sensible, you'll have to do so using a view, as synonyms only cover a subset of database-level objects.
Some other info here.

You can rename it with sp_rename and then add synonym:
CREATE SYNONYM OldTableName FOR NewTableName

Related

Is there any major issue in using EXEC sp_rename '<source table name>', '<destination table name>'?

I recently used - EXEC sp_rename '<source table name>', '<destination table name>' to rename an existing table and want to execute the same on one of our live server. Is there any issue in using this procedure to rename a table?. I am asking this because one of our DBA says there will be problems in using this procedure on live server.
Is nothing referencing the table you're renaming? That would be the only instance where I would think renaming the table would not have an impact. If the table was not referenced by anything however, what would be the purpose of the table?
you can read more about sp_rename here:
http://msdn.microsoft.com/en-us/library/ms188351.aspx
Specifically note the following:
Renaming an object such as a table or column will not automatically
rename references to that object. You must modify any objects that
reference the renamed object manually. For example, if you rename a
table column and that column is referenced in a trigger, you must
modify the trigger to reflect the new column name. Use
sys.sql_expression_dependencies to list dependencies on the object
before renaming it.
There is no major issue with renaming the table using that procedure. The only thing you need to remember is that while that command is being executed, the locks that are applied on that table won't allow you to query the data, but that should only take only a couple of milliseconds, so you should be fine.
P.S. Don't forget to modify your views, procedures, functions etc :)
Below is the only caution as described inthe microsoft official web site.
Changing any part of an object name can break scripts and stored procedures. We recommend you do not use this statement to rename stored procedures, triggers, user-defined functions, or views; instead, drop the object and re-create it with the new name.
More details at : http://msdn.microsoft.com/en-us/library/ms188351.aspx
EXEC sp_rename is recommended only when we sure that all the depended SP, View function are not get affected. Make sureyou changed or deleted the depended objects.
Perhaps your DBA can share the details of his/her concerns. Renaming a table will of course be a breaking change for any objects that reference the table so you'll need to perform due diligence to ensure dependent objects are changed to use the new name. The rename operation will also require a short schema modification lock and void existing referencing cached plans, so be aware of this if the table is heavily used.

Oracle SQL Developer doesn't put in schema names in trigger DDLs

In our test environment, the schema is prepended to the trigger DDL as one might expect. However, in our QA and PROD environments, the schema prefix doesn't show in the DDL. We always connect as the "SCHEMA" user so it hasn't been a problem thus far. Is it worth updating the QA and PROD DDL's to include the schema prefix? If we don't ever connect to the DB as a user/schema other than "SCHEMA", do we really have anything to worry about?
TEST DDL:
create or replace TRIGGER "SCHEMA"."MDATA_BIR_TRG"
BEFORE INSERT ON "SCHEMA"."METADATA"
FOR EACH ROW
BEGIN
---CODE HERE.
END;
QA DDL:
create or replace TRIGGER "MDATA_BIR_TRG"
BEFORE INSERT ON "METADATA"
FOR EACH ROW
BEGIN
---CODE HERE.
END;
I agree with omeinusch that the schema name is not that important (as long as the current schema is the same as the schema where the object is intended to reside). There is no need to recompile the trigger and make it fully qualified.
A common approach to exporting an object's DDL is to use the SQL Developer's export wizard which does allow you to indicate whether the DDL of the object is schema qualified.
Directions to obtain DDL from SQL Developer export wizard
right click on the object in the connection navigator and select export
choose characteristics of export (include schema by selecting check)
make sure file path is entered.
click next.
No, the SCHEMA is optional and only needed if you want ensure that the handled object belongs to a defined schema or not. If you "don't care" and always use mean your current schema, you can omit it.

Keep table downtime to a minimum by renaming old table, then filling a new version?

I have a handful or so of permanent tables that need to be re-built on a nightly basis.
In order to keep these tables "live" for as long as possible, and also to offer the possibility of having a backup of just the previous day's data, another developer vaguely suggested
taking a route similar to this when the nightly build happens:
create a permanent table (a build version; e.g., tbl_build_Client)
re-name the live table (tbl_Client gets re-named to tbl_Client_old)
rename the build version to become the live version (tbl_build_Client gets re-named to tbl_Client)
To rename the tables, sp_rename would be in use.
http://msdn.microsoft.com/en-us/library/ms188351.aspx
Do you see any more efficient ways to go about this,
or any serious pitfalls in the approach? Thanks in advance.
Update
Trying to flush out gbn's answer and recommendation to use synonyms,
would this be a rational approach, or am I getting some part horribly wrong?
Three real tables for "Client":
1. dbo.build_Client
2. dbo.hold_Client
3. dbo.prev_Client
Because "Client" is how other procs reference the "Client" data, the default synonym is
CREATE SYNONYM Client
FOR dbo.hold_Client
Then take these steps to refresh data yet keep un-interrupted access.
(1.a.) TRUNCATE dbo.prev_Client (it had yesterday's data)
(1.b.) INSERT INTO dbo.prev_Client the records from dbo.build_Client, as dbo.build_Client still had yesterday's data
(2.a.) TRUNCATE dbo.build_Client
(2.b.) INSERT INTO dbo.build_Client the new data build from the new data build process
(2.c.) change the synonym
DROP SYNONYM Client
CREATE SYNONYM Client
FOR dbo.build_Client
(3.a.) TRUNCATE dbo.hold_Client
(3.b.) INSERT INTO dbo.hold_Client the records from dbo.build_Client
(3.c.) change the synonym
DROP SYNONYM Client
CREATE SYNONYM Client
FOR dbo.hold_Client
Use indirection to avoid manuipulating tables directly:
Have 3 tables: Client1, Client2, Client3 with all indexes, constraints and triggers etc
Use synonyms to hide the real table eg Client, ClientOld, ClientToLoad
To generate the new table, you truncate/write to "ClientToLoad"
Then you DROP and CREATE the synonyms in a transaction so that
Client -> what was ClientToLoad
ClientOld -> what was Client
ClientToLoad -> what was ClientOld
You can use SELECT base_object_name FROM sys.synonyms WHERE name = 'Client' to work out what the current indirection is
This works on all editions of SQL Server: the other way is "partition switching" which requires enterprise edition
Some things to keep in mind:
Replication - if you use replication, I don't believe you'll be able to easily implement this strategy
Indexes - make sure that any indexes you have on the tables are carried over to your new/old tables as needed
Logging - i don't remember whether or not sp_rename is fully logged, so you may want to test that in case you need to be able to rollback, etc.
Those are the possible drawbacks I can think of off the top of my head. It otherwise seems to be an effective way to handle the situation.
Except of missing step 0. Drop tbl_Client_old if exists solutions seems fine especially if you run it in explicit transaction. There is no backup of any previous data however.
The other solution, without renames and drops, and which I personally would prefer is to:
Copy all rows from tbl_Client to tbl_Client_old;
Truncate tbl_Client.
(Optional) Remove obsolete records from tbl_Client_old.
It's better in a way that you can control how much of the old data you can store in tbl_Client_old. Which solution will be faster depends on how much data is stored in tables and what indices in tables are.
if you use SQL Server 2008, why can't you try to use horisontal partitioning? All data contains in one table, but new and old data contains in separate partitions.

How to move Database Diagram from One Server to Another Server

I have created a new Database Diagram in Test Database and it is in sitde01 Server. Now I want to move it to another server. How do I migrate it to another server.
It can be done, but it's a royal pain. Here's an outline of the process and some scripts.
Diagrams are stored in a "system" table named sysDiagrams. This table (only?) gets created when you click on the diagrams node in SSMS, it asks you if you want to create the objects that support diagrams, and you click "Yes". Do so on both your source and target databases.
Create the diagram or diagrams in the "source" database.
Review the structure and contents of sysDiagrams. Note that column diagram_id is an identity column. 1 row gets stored for every diagram. (You don't care, but it used to be 4 or 5 rows in SQL 2000.)
To copy to another database on the same SQL instance, the simplest way is to do INSERT... SELECT... between tables. With that identity column in the way, you'll have to fuss with SET IDENTITY_INSERT, and perhaps assign a new identity value on the target computer. Irritating, but not critically hard.
The following script will copy all diagrams from one database to another that's on the same server (this is how I archive complex diagrams that took waaaay too long to create, from databases that are prone to get dropped and recreated):
USE TargetDatabase
DELETE sysDiagrams
where name in (select name from SourceDatabase.dbo.sysDiagrams)
SET identity_insert sysDiagrams on
INSERT sysDiagrams (name, principal_id, diagram_id, version, definition)
select name, principal_id, diagram_id, version, definition
from SourceDatabase.dbo.sysDiagrams
SET identity_insert sysDiagrams off
To copy to another database on a different SQL instance (or server), well, it gets even harder. I use temporarily created Linked Server definitions, using scripts I sweated bullets over years ago and never want to have to modify again (i.e. post a different question so someone who knows can tell you how they work), and modify the scripts with appropriate four-part naming conventions. Other options (OPENROWSET and the like) are possible, but I'm even less familiar with those.
If you want to move your diagrams from one instance or server to a different one, and you don't want to restore the whole database, you can do the following.
If it doesn't exist, create the database on your target server. You also have to click on the "Database Diagrams" node in SSMS to have it create a dbo.sysDiagrams table.
Then make sure to import all the schema information you need in your diagram. Because your diagram will point to these. I.e. tables, PK, FK etc. must be present.
Backup your database on the source server.
Restore it into a temporary database on the target server. In this way you get all your diagram information into the target server.
Copy the information from the dbo.sysDiagrams table in the temporary database into the dbo.sysDiagram table of your target database. You could do something like this (adapted the code from Philip Kelley):
USE TargetDatabase
SET identity_insert sysDiagrams on
INSERT sysDiagrams (name, principal_id, diagram_id, version, definition)
select name, principal_id, diagram_id, version, definition
from TempDatabase.dbo.sysDiagrams
SET identity_insert sysDiagrams off
This solution worked excelent for me. Of course if you don't want all the diagrams or if other diagrams are existing in the target database, you have to filter the select statement and do some identity_insert manipulation, but this shouldn't be too difficult.
In order to move the database-diagram you will need to migrate all the tables and triggers included in that diagram. The easiest way to do this is backup the db and restore on the other server.

Renaming table column and having it propagate to dependent views

If we want to change the name of MyColumnName to MyAlteredColumnName...
...and we have a SQL Server 2008 table that looks like:
MyTable
MyColumnName
and a view that references the underlying column:
CREATE VIEW MyDependentView WITH SCHEMABINDING
AS
SELECT ..., MyTable.MyColumnName
We end up following this procedure:
Dropping the View
Altering MyTable.MyColumnName to MyTable.MyAlteredColumnName
Recreating the View with a reference to MyAlteredColumnName
We do this with migrator dot net.
Is there a better way to do this? Is there T-SQL that will alter a view column name? Or any support in SQL Server 2008 for automagically tying the columns together?
Without the use of a third-party tool, this is one of the only ways to do it. You can obviously also use ALTER VIEW instead of a DROP and CREATE.
It should be noted that Red-Gate makes a tool called SQL Refactor which will automate this sort of change (no I do not work for them). I'm sure there are other similar database refactoring tools out there.
Use sp_refreshview:
EXEC sp_refreshview #viewName
If you want to refresh all your views, you'll have to iterate over a loop of them, which means dynamic SQL.
And if you layered them (a view is dependent on another view - bad), you'll have to refresh the parent first...
If it's a SELECT * view, you can call sp_refreshview, as OMG_Ponies suggested. It will recompile the view and update the column metadata appropriately. This is one area where judicious use of SELECT * could have benefits, if used appropriately within a coherent scheme.
Otherwise, you must redefine the view. Any explicit references to the old column name will now raise an error.
Ah, one more alternative:
EXEC sp_rename 'MyTable.MyColumnName', 'MyAlteredColumnName'
ALTER TABLE MyTable ADD MyColumnName AS MyAlteredColumnName
EXEC sp_rename 'MyView.MyColumnName', 'MyAlteredColumnName'
It's a hack, and it's dangerous, since the stored view definition will now be out of sync with the view metadata. And you have littered the db with superfluous computed columns.
But it will work (until you forget what you did, or someone else has to maintain the system, and things start to break mysteriously).
I use a third party tool for this, it hasn't failed me yet. It's ApexSQL Refactor, here's the how-to tutorial
How to rename a column without breaking your SQL database