Rename column in existing table in sql server where column name is blank - sql

I want to rename column in sql server because I forgot to give name to one column. I have also tried the query below but it is not working either:
EXEC sp_RENAME 'TableName.[]' , '[Frequency of compliance]', 'COLUMN'

Using SQL Server Management Studio interactive interface, expand the DB and expand the tables and then right click on the table name to display the options, and then choose design
you can rename, change the type, add columns, including delete columns, and many others that you can do to design your table
After you finish designing, just CTRL + S to save the change, this is really simple and easiest way to design your tables

I am sure this is not possible in SQL server.
You should instead do this to find the actual column name:
select c.name from sys.columns c
join sys.tables t on c.object_id=t.object_id and t.name='TableName'
This will give you the name of all the columns from table.
You should seek the right name and then rerun sp_rename procedure.

Empty columnnames are not allowed in sql server, but they can only consist of spaces.
To rename it you can add space(s) between [].
Also you need to remove the square brackets from the new columnname, otherwise the columnname will be [Frequency of compliance] including the brackets.
But I would recommend to completely not use spaces inside columnnames.
EXEC sp_RENAME 'TableName.[ ]' , 'Frequency of compliance', 'COLUMN'
Another possibility is to use the design-mode in SSMS.

Related

Can't access the database table after I rename it

I created my table as BE Electrical. Later changed it's name to Be Electrical First. Now I can't
access What went wrong?
the table.
It is because of renaming your table has rendered its metadata useless
Use this for renaming
exec sp_rename 'Be Electrical','Be Electrical First'
instead of
exec sp_rename '[Be Electrical]','[Be Electrical First]'
After that you can use the table as intended.
For the current table that you have renamed you have to use the select query like
SELECT * FROM [dbo].[[Be Electrical First]]]
Note: try to avoid spaces in naming conventions in SQL server.

Renaming index gives error Explicit #objtype id not recognised

I am trying to rename an index and getting an error:
Error: Explicit #objtype 'idx_FinData20' is unrecognized.
I can see both the table and index exist. Then what is the problem
IF ( EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME ='FinData2000_1_old'))
BEGIN
EXEC sp_rename 'FinData2000_1_old.idx_FinData2000_1' , 'idx_FinData2000_1', 'idx_FinData20 00_1_old'
end
First - your syntax is wrong. You need only two arguments, first should be table_name.old_name and second one is just new name.
Second - you have an extra space in your new index name which breaks the script.
EXEC sp_rename 'FinData2000_1_old.idx_FinData2000_1' , 'idx_FinData2000_1_old'
Your were using the wrong syntax for SP_RENAME, by default, it accepts two inputs, the 1st one is old name, the 2nd one is new name, if you would specify the 3rd one(optional and for diffing the objects), that should be the object name.
I am not sure what is the correct case for you, but as an example, you can try this:
EXEC SP_RENAME 'INDEX_OLD_NAME', 'INDEX_NEW_NAME', 'INDEX'
As an additional notes: doing the rename will have potential risk of breaking the remaining process.
learn.microsoft.com specifies that #ObjType can only have one of the following values.
Column
Database
Index
Object
Statistics (SQL Server 2012 (11.x) and later and Azure SQL Database.)
UserDataType
There are internal processes for renaming tables and views that handle the table and view references for #ObjType automatically. So if you're renaming tables/views, leave off #ObjType since the engine is smart enough to figure it out on its own.
Also make sure to include the schema (even if its just dbo so it becomes second nature to you to include it in the future...) in #ObjName since there may be the same named tables in different schemas.
It is also worthy to note that once you rename a table, any indexes you made on the old table are automatically updated to reference the new table name that you just updated it to.
I've finally worked out that some objects need to be quoted. This can be done with the QUOTENAME() function.
For example, I have a primary key constraint created by EF6 named PK_dbo.SafetyDataSheets.
To rename this constraint name the following can be used:
EXEC sp_rename 'dbo.' + QUOTENAME(`PK_dbo.SafetyDataSheets`), 'PK_SafetyDataSheets'

alter table with space in name

I have a table with a space in the name generated by a system.
I am trying to alter the table name to remove the space so that it can be processed by a library the pre-exists.
I am trying:
ALTER TABLE 'My Table'
RENAME TO 'MyTable';
I have also tried double quotes, no luck.
Any pointers?
[This will not work in MS-Access. Tables cannot be renamed in Access. Not clear if original question applied to MS Access.]
Square brackets:
ALTER TABLE [My Table]
RENAME TO [MyTable];
Square brackets can't enclose the entire object "path" so this won't work:
ALTER TABLE [MyDatabase.dbo.My Table]
but this will
ALTER TABLE [MyDatabase].[dbo].[My Table]
For MySQL, single quotes, double quotes or brackets did NOT work for me. Only backticks (aka backquotes) worked.
So, try this:
ALTER TABLE `My Table`
RENAME TO MyTable;
[My Table]
You can use square brackets in SQL to get around this.
It has many functions, you can use keywords in tables, put spaces and periods in table names or schemas, etc.
For example you can have the schema [Work.Employees]. With the square bracket it would be [Work.Employees].Addresses (schema, table). However, if you forget the brackets it will attempt to find the database Work -> schema Employees -> Table Addresses.
However, it is generally good practice to avoid doing any of the above :)
This is one of those things that is a lot easier to achieve using the Access GUI!
To do the same in SQL DDL you must 'clone' the table, for which you must already have knowledge of all the attribute names, types, constraints, etc, noting it may have features that are not creatable via SQL DDL e.g. Validation Rules. Then you need to populate it using the original table. The you drop the original. Phew!

Using name of a database inside a sql script for a full table name

I struggled for a while with a bug, and then found out the reason for it in a database stored procedure code, which contained the old name of a database in a table name, whereas the current database name was already different. So, I'd like to ask:
Is there a situation in which using a database name as a part of a full table name (database name + schema name + table name) can be justified (provided we don't touch tables in other databases) or is it always a bad practice? How to correctly use a database name in sql scripts to keep code neutral to a specific database?
Code just for an illustration:
CREATE PROCEDURE [dbo].[MyProc]
AS
BEGIN
DELETE FROM [MyDatabase].[dbo].[MyTable]
END
No, you shouldn't use database names in a stored procedure unless you need to address two databases.
It causes exactly the kinds of bugs you're seeing. When the database name changes, all your SP code breaks, or continues working, but on the old database.
It does make sense if you are sending a SQL query to the database, but only if the application dynamically picks the database name to insert into the query.
My suggestion is that you do a full export of your database schema, and search for database names that are hardcoded and remove them.
It really depends on how your scripts are implemented.
Even if you don't refer to a table as
[MyDatabase].[dbo].[MyTable]
you will still need to refer to the database by:
USE [MyDatabase]
earlier in the script.
It is possible to mix trusted database tables in a single query. When someone do this,it is justified and mandatory to include database on table 'path'.
I don't found a reason out of this scenario if stored procedure and table is on the same database.
You can search all database name occurencies through database catalog in order to fix your development. For SQL Server 2005:
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%databasename%'
GO
For SQL Server 2000:
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%databasename%'
GO

Alter SQL Server table column width with indexes

I am using SQL Server 2008 and need to alter a large number of columns across many tables from decimal(9,3) to decimal(12,6)
The issue I currently have is that some tables have several indexes on these columns and the alter statement fails due to the index.
Is there a way to alter the column without losing the index?
I am altering the column as follows:
alter table [TABLE_NAME] alter column [Conf_Tonnes] decimal(12,6) not null
I believe it is not possible to change the type of a column whilst it has any constraint on it. Certainly it used to be the case with earlier versions of SQL Server, and I don't think it has changed.
For practical purposes, you can use a script to list all fields of a certain type:
DECLARE #name AS varchar(20)
SET #name = '<Name of type>'
select T.name as "Table", F.name as "Field"
from sys.tables T left join sys.columns F on T.object_id=F.object_id
where F.user_type_id=(select user_type_id from sys.types where name=#name)
Which will give you the list of fields which need changing.
You can also drop constraints from fields but the difficult thing is how to recreate them.
if you have external meta-descriptions of the database, then you can use that to generate scripts easily. Alternatively, you could run the script generate tool - select all tables on, all options off, except tables and indexes - this should generate the full list of tables and indexes for you.
You can find it by right-clicking on the database in object explorer/tasks/generate scripts.
Unfortunately I don't think you can get index scripts generated without having table create scripts created as well - but Visual Studio text editing scripts shoudl make the job of cutting out the bits you don't want fairly easy.
Given time, it's probably possible to put together some scripts to do the whole job automatically, and it would give you a decent set of tools for future use.