Delete column in SQL that contains dots and squared brackets - sql

How can one delete a column name [database].[dbo].[my_table].[col_name] in SQL server, that is a column name with dots and squared brackets. In other words, it is the column name that I wanted but prefixed by the database name and shema.
I tried many combinations based on internet e.g. here but didn't succeed.
Thank you.

I don't understand if you want to rename this column or drop it, but here is how to do both
CREATE TABLE JustTest(
Col1 INT,
[[database]].[dbo]].[my_table]].[col_name]]] INT
);
-- To rename the column use this
EXEC sp_rename 'JustTest.[[database]].[dbo]].[my_table]].[col_name]]]',
'NewName',
'COLUMN';
-- If the table is TempTable use this
EXEC tempdb.sys.sp_rename N'#TMP.[[database]].[dbo]].[my_table]].[col_name]]]',
N'NewName',
N'COLUMN';
-- To drop it use this
ALTER TABLE JustTest DROP COLUMN [[database]].[dbo]].[my_table]].[col_name]]];

In a delimited identifier ']' is escaped as ']]', '[' and '.' don't need to be escaped.
So like this:
create table #tt(id int, [[database]].[dbo]].[my_table]].[col_name]]] int)
alter table #tt drop column [[database]].[dbo]].[my_table]].[col_name]]]

Related

Dropping column with quotation marks in column name

I added a column using following commands (I used quotation marks so that N is in upper case in my column name)
ALTER TABLE new_table
ADD “Name” VARCHAR(50);
However, I see "nam" column in my table now after running that command.
How can I drop that column?
ALTER TABLE new_table
DROP COLUMN "Name";
I get following error:
ERROR: column "name" of relation "new_table" does not exist
The following statement causes this error:
ALTER TABLE new_table
DROP COLUMN "Name";
seems you are not using double quote " in first query bus some others quotes try suing the same chars “”
ALTER TABLE new_table DROP COLUMN “Name”;
Check how Postgres is storing the column name when you are using a double quote in column name:
select table_name, column_name from information_schema.columns where
table_name='tab1';
Also, you may view the same when you execute a select statement:
select * from table;
Copy the same column name text in your alter statement. Here is the sample column name with both kind of double quotes in PostgreSQL:
create table tab1(data varchar(30));
alter table tab1 ADD “Name1” varchar(50);
alter table tab1 ADD "Name2" varchar(50);
select *from tab1;
select table_name, column_name from information_schema.columns where table_name='tab1';
alter table tab1 drop column “Name1”;
alter table tab1 drop column "Name2";
table_name column_name
tab1 data
tab1 “name1”
tab1 Name2
Here is the link to the fiddle
Note: Avoid using a double quote in the table name, column, etc. In case you use you have to ensure that the same names are specified in all queries.
Edit:
It's simple. If you use "Name" (not same as “Name”, notice quote angle) in the column name then you have to refer the column as "Name". In case “Name” is used then you have to refer by “Name”. The quotes need to match.
Another observation is when "Name" used as column name it makes the column name as Name (N uppercase) as opposed to all lowercase column names by default in the database but needs to be referred as "Name".

How can I change column comments in existing Hive table without including new column name and type?

I want to change the column comments on an existing hive table using hive 0.13. This works:
create table test (mycolumn int);
alter table test change mycolumn mycolumn int comment 'hello';
But I can't find a way to do this without repeating the name of the column and the type, both of which are irrelevant to the change. For example:
alter table test change mycolumn comment 'hello'; leads to an error.
If this was for one column it would not be a big deal but I want to do this for large numbers of columns in tables that were not commented. I know this could be done with a script that simply copies the column name and its type but would be nice to know if there were something simpler. Thanks
You can do this using ALTER command.
CREATE TABLE my_table
(id INT COMMENT 'id comment',
name STRING comment 'name comment');
-- change column comment as below.
ALTER TABLE my_table CHANGE id id INT COMMENT 'another comment';
-- see changed column
DESC EXTENDED my_table;
ALTER TABLE test_change CHANGE a1 a1 INT COMMENT 'this is column a1';
Directly its not supported to edit column property for comment the other way around is
alter table dev.travel change num2 clm_num1 int comment 'a new column added';
Now I want to change above one lets do ;
alter table dev.tkt change clm_num1 num2 int comment 'a new column added';
alter table dev.tkt change num2 clm_num1 int comment 'a new column added with new comment';

alter data type of existing column from bigint to varchar in Apache derby

I am using Apache derby database v 10.9.1.0. There is one existing table Country-having column LawID of type bigint. It contains records having integer data only. Due to some business reason, I need to alter its data type from 'bigint' to 'varchar' . I tried following two ways to alter existing table. But both ways did not work.
a. first way
ALTER TABLE Country ADD COLUMN LawID_NEW VARCHAR(50);
UPDATE Country SET LawID_NEW = LawID;
ALTER TABLE Country DROP COLUMN LawID;
RENAME COLUMN Country.LawID_NEW TO LawID;
It shows message like :Columns of type 'VARCHAR' cannot hold values of type 'BIGINT'.
b. second way
ALTER TABLE Country ALTER LawID SET DATA TYPE VARCHAR(50);
It shows error message like : Invalid type specified for column 'LawID'. The type of a column may not be changed.
Any help related to correct alter query is highly appreciated, Thanks
I think the first method would work with this change:
UPDATE Country SET LawID_NEW = TRIM(CHAR(LawID));
ALTER TABLE tablename MODIFY columnname VARCHAR(20);
This works in mysql. Give it a try.
Or
ALTER TABLE table CHANGE columnname columnname VARCHAR(20);

SQL: ALTER COLUMN to shorter CHAR(n) type

I'm working with MS SQL SERVER 2003. I want to change a column in one of my tables to have fewer characters in the entries. This is identical to this question: Altering a Table Column to Accept More Characters except for the fact that I want fewer characters instead of more.
I have a column in one of my tables that holds nine-digit entries. A developer previously working on the table mistakenly set the column to hold ten-digit entries. I need to change the type from CHAR(10) to CHAR(9).
Following the instructions from the discussion linked above, I wrote the statement
ALTER TABLE [MY_TABLE] ALTER COLUMN [MY_COLUMN] CHAR(9);
This returns the error message "String or binary data would be truncated". I see that my nine-digit strings have a space appended to make them ten digits.
How do I tell SQL Server to discard the extra space and convert my column to a CHAR(9) type?
I think you get the error because there are some values in that table that are exactly 10 chars long (with no trailing spaces). Altering the table would thus cut these values to the length 9.
This is not allowed by default. If there only would be strings which would have some trailing spaces, there would be no problem with that.
So, if you are ok with cutting those values, do
UPDATE MY_TABLE SET MY_COLUMN = LEFT(MY_COLUMN, 9)
first, after that do the alter.
Disable Ansi Warnings before you alter your table.
SET ANSI_WARNINGS OFF
Beware that data will be truncated if you happen to have something 10 characters long.
Edit
Check existing lengths before actually changing the column length.
SET ANSI_WARNINGS OFF
GO
CREATE TABLE Test (Value CHAR(10))
INSERT INTO Test SELECT ('1234567890')
IF NOT EXISTS (SELECT * FROM Test WHERE LEN(Value) > 9)
ALTER TABLE Test ALTER COLUMN Value CHAR(9)
ELSE
SELECT LEN(Value), * FROM Test WHERE LEN(Value) > 9
DROP TABLE Test
The above 2 answers didn't work for me because I had a history table attached to the table I was trying to alter. This is what I did:
UPDATE MY_TABLE SET MY_COLUMN = LEFT(MY_COLUMN, 9)
ALTER TABLE MY_TABLE SET (SYSTEM_VERSIONING = OFF)
-- Might need to UPDATE MY_TABLEHistory SET MY_COLUMN = LEFT(MY_COLUMN, 9)
-- I didn't
ALTER TABLE MY_TABLEHistory ALTER COLUMN [MY_COLUMN] [varchar] (9) NULL
ALTER TABLE MY_TABLE SET (SYSTEM_VERSIONING = ON(HISTORY_TABLE = MY_TABLEHistory))
ALTER TABLE MY_TABLE ALTER COLUMN [MY_COLUMN] [varchar] (9) NULL

is this a problem in the sp_rename function or sql server itself?

While renaming the column name, the square bracket is included in the column name, which I think is a bug,
Here is a sample code snippet,
create table [TestTable]
(TestColumnName nvarchar(30))
select TestColumnName from TestTable
sp_rename '[TestTable].[TestColumnName]', '[RenamedColumnName]', 'Column'
select [RenamedColumnName] from TestTable -- does not work "Invalid column name 'RenamedColumnName'."
select RenamedColumnName from TestTable -- does not work "Invalid column name 'RenamedColumnName'."
select * from [TestTable] -- works fine!!!
The bug here is that the column rename includes the square brackets, I found this which says that the "first character must be one of the following", but "[" does not seem be included in the list, is there a problem with sp_rename or sql server itself?, as it allows alteration of column name to start with a square bracket.
The column in your code has been renamed to one that actually includes [] - to query this column you'll have to use
SELECT [[RenamedColumnName]]] FROM TestTable
] is a delimited identifier, so you have to escape it. For ], this means an additional ] for each one used in the name.
If you want to fix this, you can do this:
IF EXISTS(SELECT * FROM sys.columns where name ='[MyColumn]' AND [object_id]=OBJECT_ID('[MyTable]'))
BEGIN
EXEC sp_rename 'MyTable.[[MyColumn]]]', 'MyColumn', 'COLUMN';
END
Don't ask me why it works, it just does.
Data error !!!
Its not
sp_rename '[TestTable].[TestColumnName]', '[RenamedColumnName]', 'Column'
It should be like this
sp_rename '[TestTable].[TestColumnName]', 'RenamedColumnName', 'Column'
then
select [RenamedColumnName] from TestTable -- works fine!!!
select RenamedColumnName from TestTable -- works fine!!!
select * from [TestTable] -- works fine!!!
Even though the new column name is with space like "Renamed ColumnName" NO NEED TO use the square brackets in the
It's not a bug, as "[" and "]" are valid characters within a column name. sp_rename has to work by receiving the exact column name you want to use - after all how would it know whether you wanted a column actually called "[MyColumnWithBrackets]" or "MyColumnWithBrackets". Hence, if you provide a name, it's treated literally and does not require you to manually enclose (e.g.) column names with spaces in, in brackets
the square brackets are used to mark the boundaries of the columns names. That way you can include reserved words, spaces, single quotes etc. in the column names and the script will not fail.
sp_rename: http://msdn.microsoft.com/en-us/library/aa238878(SQL.80).aspx
from BOL: This example renames the
contact title column in the customers
table to title: EXEC sp_rename
'customers.[contact title]', 'title',
'COLUMN'
try this:
sp_rename 'TestTable.TestColumnName', 'RenamedColumnName', 'Column'
since you are passing in strings into the procedure you don't need the square braces "[","]"
you can use "[","]" in the first parameter, but if you use them in the second parameter, they become part of the actual column name:
create table [TestTable2]([Test ColumnName] nvarchar(30))
exec sp_help testtable2
exec sp_rename 'dbo.TestTable2.[Test ColumnName]', 'Renamed ColumnName', 'Column'
exec sp_help testtable2