general useable alias names for tables and columns - sql

if we define tables with columns we have to use company specific naming conventions.
new employees have often problems in understanding all this table and columnnames.
so i had the idea that it would be great if we could define that a table 'Customer' could always be referenced by 'Kunde' and the
Column 'SPR' referenced by 'spezialPreis'.
And i want to define these alias names in the database schema so that nobody has to know the oldstyled orginal names.
is something like this possible?
special interessted is a solution with ms sql server.
additional Information: the main goal is not to bypass a naming convention. it is to let old application work with old namings and let us make new ones with new and better understanding namings.
additional we can't use views, because we want to use it in all statements. insert, update, delete, alter, grant,... what ever..

I would suggest adding a computed column:
alter table customer add kunde as (old_column_name_here)
You cannot readily remove the old name, unless you use a view. But this at least adds the new name, so you can migrate to using it (and, perhaps, eventually rename the old name to kunde).

Related

Can I create new table on SQL without specifying the datatype?

I want to create new table with empty columns and specify the datatype later. Is it possible? I try to do so on myscompiler.io and it works. I don't know if it's just possible in such site or is it actually possible to create that once I use other tools to write my SQL.
No. The SQL syntax requires that a table be well-defined, with column names and data types. This is true in every database that I can think of.
You could possibly do what you want in one of three ways:
Your database might support some sort of generic type which you could use to define the column. For instance, SQL Server has a sql_variant type.
You could define the table with a specific type such as a string and change the type later using alter table.
You could define the table with a single primary key column and add columns as you decide what they are.
I don't recommend any of these approaches. Instead, I would suggest that you need to re-think how your application is structured. Tables represent entities and entities have properties. Generally when using databases, these things are known before you start doing any work. There may be some cases where dynamic table creation is useful, but that is definitely not the common approach when using databases.

How to enforce backwards compatibility with View

How could I apply View to enforce backwards compatibility with old queries that rely on old schema if the following change happens:
T(A1(key), A2)
to
T(A1(key), A2(key))
Basically we would make second attribute to be a joined key with first attribute.
Is there any standard way of doing it across diff sql languages?
If not I am interested in SQLite/SQLite3.
Thanks you!
I would have thought that you'd treat this no different to a table, other than not having to worry about the actual data.
That is include it in the older schema to work with the older schema and then upgrade it to the new schema along with the tables by using
DROP VIEW IF EXISTS your_view;
CREATE VIEW IF NOT EXISTS your_view .............;
For other SQL, again as for tables, you may find it simpler to just use the often more extensive ALTER commands.
Without specifics it's hard to say whether or not a single standard method could be adopted.

Is it possible to make full recursive alias for an entire Database?

Hi my question is very weird but necessary.
The database was made by a person who named tables and fields like "EMP.EMPCOD0001". Of course that's a low level work but there is no way to change the system and the guy is supported by the company's owner, and IT needs to work properly.
Is it possible to create a kind of shadow table which links to another with reasonable names like: "employee.id_number" pointing to the crappy table?
Use views, e.g.
CREATE VIEW emp.GoodName (goodCol1, goodCol2, goodColEtc)
as SELECT lameCol1, lameCol2, lameColEtc
from emp.LameName
You could put all the views in the dbo schema, but--if it's well thought out or used for security--you might want to maintain the existing schemas.
(Edited to show that columns can be "mapped" as well.)

SQL Server - Schema/Code Analysis Rules - What would your rules include?

We're using Visual Studio Database Edition (DBPro) to manage our schema. This is a great tool that, among the many things it can do, can analyse our schema and T-SQL code based on rules (much like what FxCop does with C# code), and flag certain things as warnings and errors.
Some example rules might be that every table must have a primary key, no underscore's in column names, every stored procedure must have comments etc.
The number of rules built into DBPro is fairly small, and a bit odd. Fortunately DBPro has an API that allows the developer to create their own. I'm curious as to the types of rules you and your DB team would create (both schema rules and T-SQL rules). Looking at some of your rules might help us decide what we should consider.
Thanks - Randy
Some of mine. Not all could be tested programmatically:
No hungarian-style prefixes (like "tbl" for table, "vw" for view)
If there is any chance this would ever be ported to Oracle, no identifiers longer than 30 characters.
All table and column names expressed in lower-case letters only
Underscores between words in column and table names--we differ on this one obviously
Table names are singular ("customer" not "customers")
Words that make up table, column, and view names are not abbreviated, concatenated, or acronym-based unless necessary.
Indexes will be prefixed with “IX_”.
Primary Keys are prefixed with “PK_”.
Foreign Keys are prefixed with “FK_”.
Unique Constraints are prefixed with “UC_”.
I suspect most of my list would be hard to put in a rules engine, but here goes:
If possible I'd have it report any tables that are defined as wider than the bytes that can be stored in a record (excluding varchar(max) and text type fields) and/or a datapage.
I want all related PK and FK columns to have the same name if at all possible. The only time it isn't possible is when you need to have two FKs in the same table relating to one PK and even then, I would name it the name of the PK and a prefix or suffix describing the difference. For instance if I had a PersonID PK and a table needed to have both the sales rep id and the customer id, they would be CustomerPersonID, and RepPersonID.
I would check to make sure all FKs have an index.
I would want to know about all fields that are required but have no default value. Depending on what it is, you may not want to define a default, But I would want to be able to easily see which ones don't to hopefully find the ones that should have a default.
I would want all triggers checked to see that they are set-based and not designed to run for one row at time.
No table without a defined Unique index or PK. No table where the PK is more than one field. No table where the PK is not an int.
No object names that use reserved words for the database I'm using.
No fields with the word Date as part of the name that are not defined as date or datetime.
No table without an associated audit table.
No field called SSN, SocialSecurityNumber, etc. that is not encrypted. Same for any field named CreditCardNumber.
No user defined datatypes (In SQL Server at least, these are far more trouble than they are worth.)
No views that call other views. Experience has shown me these are often a performance disaster waiting to happen. Especially if they layer more than one layer deep.
If using replication, no table without a GUID field.
All tables should have a DateInserted field and InsertedBy field (even with auditing, it is often easier to research data problems if this info is easily available.)
Consistent use of the same case in naming. It doesn't matter which as long as all use the same one.
No tables with a field called ID. Hate these with a passion. They are so useless. ID fields should be named tablenameID if a PK and with the PK name if an FK.
No spaces or special characters in object names. In other words if you need special handling for the database to recognize it in the correct context in query, don't use it.
If it is going to analyze code as well, I'd want to see any code that uses a cursor or a correlated subquery. Why create performance problems from the start?
I would want to see if a proc uses dynamic SQl and if so if it has an input bit variable called Debug (and code to only print the dynamic SQl statment and not execute it, if the Debug variable is set to 1).
I'd want to be able to check that if there is more than one statement causing action in the database (insert/update/delete) that there is also an explicit transaction in the proc and error trapping to roll the whole thing back if any part of it fails.
I'm sure I could think of more.

SQL, How to change column in SQL table without breaking other dependencies?

I'm sure this might be quite common query but couldn't find good answer as for now.
Here is my question:
I've got a table named Contacts with varchar column Title. Now in the middle of development I want to replace field Title with TitleID which is foreign key to ContactTitles table. At the moment table Contacts has over 60 dependencies (other tables, views functions).
How can I do that the safest and easiest way?
We use: MSSQL 2005, data has already been migrated, just want to change schema.
Edit:
Thanks to All for quick replay.
Like it was mentioned Contacts table has over 60 dependents, but when following query was run, only 5 of them use Title column. Migration script was run, so no data changes required.
/*gets all objects which use specified column */
SELECT Name
FROM syscomments sc
JOIN sysobjects so ON sc.id = so.id
WHERE TEXT LIKE '%Title%' AND TEXT LIKE '%TitleID%'
Then I went through those 5 views and updated them manually.
Use refactoring methods. Start off by creating a new field called TitleID, then copy all the titles into the ContactTitles table. Then, one by one, update each of the dependencies to use the TitleID field. Just make sure you've still got a working system after each step.
If the data is going to be changing, you'll have to be careful and make sure that any changes to the Title column also change the ContactTitles table. You'll only have to keep them in sync while you're doing the refactoring.
Edit: There's even a book about it! Refactoring Databases.
As others pointed out it depends on your RDBMS.
There are two approaches:
make a change to the table and fix all dependencies
make a view that you can use instead of direct access to the table (this can guard you against future changes in the underlying core table(s), but you might loose some update functionality, depending on your DBMS)
For Microsoft SQL Server Redgate have a (not free) product that can help with this refactoring http://www.red-gate.com/products/sql_refactor/index.htm
In the past I have managed to do this quite easily (if primitively) by simply getting a list of things to review
SELECT * FROM sys.objects
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Contacts%'
(and possibly taking dependencies information into account and filtering by object type)
Scripting all the ones of interest in Management Studio then simply going down the list and reviewing them all and changing the CREATE to ALTER. It should be quite a simple and repetitive change even for 60 possible dependencies. Additionally if you are referring to a non existent column you should get an error message when you run the script to ALTER.
If you use * in your queries or adhoc SQL in your applications obviously things may be a bit more difficult.
Use SP_Depend 'Table Name' to check the Dependencies of the table
and then Use the SP_Rename to Rename the Column Name which is very useful.
sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the PRIMARY KEY constraint is also automatically renamed by sp_rename.
and then start Updating the Procedure and Functions one by one there is no other good option for change like this if you found then tell me too.