using new columns in the temp table added by alter table not work - sql-server-2000

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.

Related

How to copy SQL column data to new column then drop the original column?

I am following the recommendation in this sql snowflake forum in order to transform an integer data column into a varchar by creating a new column. I want to drop the original integer column when I am done, but doing so always results in the new column no longer working and any future queries erroring out.
For instance, I have test_num is the integer and test_num_to_char is the varchar
alter table test_table
add test_num_to_char varchar as CAST(test_num as varchar)
then
alter table test_table
drop column test_num
select *
from test_table
results in an error message:
SQL execution internal error: Processing aborted due to error 300002:224117369
Is there a different transformation method that removes the dependency on the original integer column so I can drop it?
alter table test_table add test_num_to_char varchar(10);
go
update test_table set test_num_to_char = CAST(recno as varchar);
Try the TO_DECIMAL transformation method.
It's documentation is given here

Cannot add NOT NULL constraint [duplicate]

So I want to change a column in my SQL Server database to not allow nulls, but I keep getting an error. this is the sql statement I am using:
alter table [dbo].[mydatabase] alter column WeekInt int not null
and this is the error I am getting :
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'WeekInt', table 'CustomerRadar.dbo.tblRWCampaignMessages'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
I'm pretty sure my sql is right, and there are no nulls currently in the column I am trying to change so I am really not sure as to what is causing the problem. Any ideas? I'm stumped.
Clearly, the table has NULL values in it. Which you can check with:
select *
from mydatabase
where WeekInt is NULL;
Then, you can do one of two things. Either change the values:
update mydatabase
set WeekInt = -1
where WeekInt is null;
Or delete the offending rows:
delete from mydatabase
where WeekInt is null;
Then, when all the values are okay, you can do the alter table statement.
If you are trying to change a column to not null, and you are getting this error message, yet it appears the column has no nulls, ensure you are checking for is null and not = null (which gives different results).
Select * from ... where column is null
instead of
Select * from ... where column = null
I am adding this because it tripped me up and took a while to resolve.
This will work. You should send a default value, then it will change all the previous record to -1 in this example.
alter table [dbo].[mydatabase] alter column WeekInt int not null DEFAULT '-1';

SQL Code Evaluation stopping a valid transaction

As part of the company I am working for at the moment I need to create some database upgrade scripts to replace some work of a previous contractor.
The code before the following block runs, creates the new ID column, and then this script looks to populate the values and then drop some columns.
IF EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(N'[Central].[Core.Report].[ReportLessonComp]')
AND name = 'Name')
and
EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(N'[Central].[Core.Report].[ReportLessonComp]')
AND name = 'Code')
BEGIN
UPDATE
[Central].[Core.Report].[ReportLessonComp]
SET
CompetencyId = rc.Id
FROM
[Central].[Core.Report].[ReportLessonComp] rlc
INNER JOIN
[Core.Lookup].ReportCompetency rc
ON
rc.Code = rlc.Code and rc.Name = rlc.Name
ALTER TABLE [Central].[Core.Report].[ReportLessonComp] DROP COLUMN CODE
ALTER TABLE [Central].[Core.Report].[ReportLessonComp] DROP COLUMN [Name]
ALTER TABLE [Central].[Core.Report].[ReportLessonComp] DROP COLUMN [Description]
END
GO
When running the if exists \ not exists checks and then select getdate() this works perfeclty fine and gives me the result I expect.
However, when I run the code block above I get error
Msg 207, Level 16, State 1, Line 23
Invalid column name 'Code'.
Msg 207, Level 16, State 1, Line 23
Invalid column name 'Name'.
This script it part of a larger upgrade script and is used in a system calle RoundHouse https://github.com/chucknorris/roundhouse which is the system chosen by the company.
Prior to the above if exists check,
IF (SELECT COUNT(1) FROM sys.columns
WHERE OBJECT_ID = OBJECT_ID('[Central].[Core.Report].[ReportLessonComp]')
AND Name in ('Name','Code')) = 2
which also gave the same issue. I have five tables that I need to update and this is going to stop the team from working if I cant resolve this at my next PR
What can I do in order to stop this from causing the upgrade scripts to fail?
EDIT -- The reason I am linking on varchar fields also is because the previous developer did not create relationships between tables, and was just inserting strings into tables rather than relating by ID causing the potential for unlinked \ inconsistent data.
The table edit prior to this creates the new id column, and this script is getting the value and dropping columns that are no longer needed
SQL Server will parse the whole of the statement prior to execution, so the exists check does not protect you from the update being parsed. If the column has already been dropped, that makes the statement invalid and you get a parse error. The update statement would have to be executed as dynamic SQL, sp_execute basically so that the varchar of the update is not directly parsed.
For SQL Server 2016 and above the drop column can be protected a bit more as well:
ALTER TABLE [Central].[Core.Report].[ReportLessonComp] DROP COLUMN IF EXISTS CODE

change column name in sql server without using sp_rename

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...

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