change column name in sql server without using sp_rename - sql

I want to change my column name in sql server using a query, without using sp_rename command. Can you please tell me if anybody know it?
I tried as:
alter table table_name alter column 'column1' to 'column2'
and it gave an error message as:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'column1'.

It is not possible to rename a column using the ALTER TABLE statement in SQL Server. Reference.
Use sp_rename instead.
OR
You can right click on the table -> select rename -> type new name.
And example is here.

alter table table_name add column 'column2'
update table_name set column2 = column1
alter table table_name drop column column1
PSEUDOCODE, need data types, likely to turn off triggers, etc. Quite ugly, but does "get the job done".
NOT very good for large tables, of course...

Related

Check if column exists then alter column from the table?

I want to write sql script that should check if column exists in the table, and then remove the column if previous statement is true. The database I use is Sybase ASE, and this is the code that I tried to use:
IF EXISTS (SELECT 1 FROM syscolumns WHERE id = object_id('users') AND name = 'maiden_name')
BEGIN
ALTER TABLE security DROP maiden_name
END
The code above executed successfully first time I run it. The second time I goth the error:
Invalid column name 'maiden_name'
If column does not exist the ALTER TABLE block of code shouldn't run. Is there a way to achieve this is Sybase? Thank you.
You can use dynamic SQL:
IF EXISTS (SELECT 1 FROM syscolumns WHERE id = object_id('users') AND name = 'maiden_name')
BEGIN
EXEC('ALTER TABLE security DROP maiden_name')
END;
The problem is that the parser is trying to parse the ALTER during the compilation phase, and it gets an error if the column does not exist.

using new columns in the temp table added by alter table not work

I have a problem that the new added column can't be used in the further comments.
I have a temp table built by "select into" then I need to add an identity column by "alter table". But when I want to use the new column in a "join", I got an error "Invalid column". please note that, these commands could work separately.
I think the reason is, the new column is not found by the compiler and it give an error before running it.
Is there a solution for that ?
I have got this problem in sql server 2000 and it seems in a newer version, the problem is not there.
create table #tmp_tb
(name varchar(4), val int)
insert into #tmp_tb values('ab',1);
insert into #tmp_tb values('abc',2);
select * from #tmp_tb
alter table #tmp_tb add id int NOT NULL IDENTITY(1,1);
select * from #tmp_tb
select id,name,val from #tmp_tb
An error occurred :
Msg 207, Level 16, State 3, Line 9
Invalid column name 'id'.
Replace the last line with
EXECUTE sp_executesql N'select id,name,val from #tmp_tb';
Indeed, the parser doesn't know about the new column yet. By passing it through sp_executesql you avoid this.

SQL SERVER: I would like to transfer my data to another column of the same table before droping the first one

I am having problems with some of my SQL scripts on SQL SERVER, indeed I am trying to transfer data from a column A to a column B of the same table and then drop the column B,
However my problem is that I have to check for the existence of A beforehand because the code is meant to be executed on a server where I don't have access (I work as a third party developper on a professionnal app)
Here is my code:
-- Export the data from the column name
-- Drop the column name
USE p_mynacellelocation_db_ChecklistWPF
GO
IF COL_LENGTH('model_trolley_part','name') IS NOT NULL
BEGIN
UPDATE model_trolley_part
SET name_en=[name];
ALTER TABLE model_trolley_part
DROP COLUMN [name];
END
In the case of the column name being non existent I would like not to do anything
However on execution of the code in a database where the column name is non existent SQL Server returns me:
Msg 207, Level 16, State 1, Line 12 Invalid column name 'name'.
Instead of jumping through all these hoops simply rename your original column.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-2017
exec sp_rename 'model_trolley_part.name', 'name_en', 'COLUMN'
You need to use dynamic SQL for this. The reason is that the parser will try to validate your code, even the code that won't be executed because its IF condition wouldn't be met.
The parser is smart enough to see there is no table named name, but it's not smart enough to realize that the code shouldn't get executed because of the IF, so it raises a parsing error.
Using dynamic SQL in the BEGIN..END block after the IF hides this from the parser so it will execute.
Try this:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'ColumnA')
BEGIN
// your update and drop code goes here
END
you might want to check your account privileges if you are modifying table structure etc..

set column to 'not null' in SQL Server

I have a column in a table in a sql server database that I want to set to 'not null'. However, when I execute the query
ALTER TABLE mytable ALTER COLUMN mycolumn INT NOT NULL
I get an
ALTER TABLE ALTER COLUMN mycolumn failed because one or more objects access this column.
How can I find out what kind of object that is and how do I drop it? The database is very simple and is not supposed to make use of foreign keys, triggers etc.
You could search the sys tables to find out what is dependent on the column. This has its limitations, naturally, but by-and-large should give you some indication of what is dependent on your column:
SELECT
OBJECT_NAME(D.Object_ID) AS [Dependent]
,D.Object_ID
FROM sys.sql_dependencies D
INNER JOIN sys.Columns C
ON C.object_id = D.referenced_major_id
AND C.column_id = D.referenced_minor_id
WHERE OBJECT_NAME(C.object_id) = 'MyTable'
AND C.name = 'MyColumn'
;
Once you have the name and object_id of the dependent (it might be a function, a stored procedure, or any number of things) you can go from there.
You might have to drop constraints on the column first,before altering this table.This may be a constraint,index or any thing..below is a small demo showing the same
create table #test
(
id int,
id1 int
)
create index nci_t on #test(id1)
include(id)
alter table #test
alter column id1 varchar(10)
this is the error i got
Msg 5074, Level 16, State 1, Line 2
The index 'nci_t' is dependent on column 'id1'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE ALTER COLUMN id1 failed because one or more objects access this column.
also please paste entire error message ,don't strip it

Stored Procedure consist Add column, Update data for that column, and Select all data from that table

I've written a stored procedure as following:
CREATE PROC spSoNguoiThan
#SNT int
AS
begin
IF not exists (select column_name from INFORMATION_SCHEMA.columns where
table_name = 'NhanVien' and column_name = 'SoNguoiThan')
ALTER TABLE NhanVien ADD SoNguoiThan int
else
begin
UPDATE NhanVien
SET NhanVien.SoNguoiThan = (SELECT Count(MaNguoiThan)FROM NguoiThan
WHERE MaNV=NhanVien.MaNV
GROUP BY NhanVien.MaNV)
end
SELECT *
FROM NhanVien
WHERE SoNguoiThan>#SNT
end
GO
Then I get the error :
Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 12
Invalid column name 'SoNguoiThan'.
Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 15
Invalid column name 'SoNguoiThan'.
Who can help me?
Thanks!
When the stored proc is parsed during CREATE the column does not exist so you get an error.
Running the internal code line by line works because they are separate. The 2nd batch (UPDATE) runs because the column exists.
The only way around this would be to use dynamic SQL for the update and select so it's not parsed until EXECUTE time (not CREATE time like now).
However, this is something I really would not do: DDL and DML in the same bit of code
I ran into this same issue and found that in addition to using dynamic sql I could solve it by cross joining to a temp table that had only one row. That caused the script compiler to not try to resolve the renamed column at compile time. Below is an example of what I did to solve the issue without using dynamic SQL
select '1' as SomeText into #dummytable
update q set q.ValueTXT = convert(varchar(255), q.ValueTXTTMP) from [dbo].[SomeImportantTable] q cross join #dummytable p