Invalid object name when updating after renaming table - sql

Have a very strange problem when trying to rename table and use it.
I have a table called oldTable and rename it to the newTable.
I can successfully use select on this table using:
SELECT * FROM database.dbo.newTable;
But when I try to use update like this:
UPDATE database.dbo.newTable SET foo = bar where id = 1;
I receive following error:
Msg 208, Level 16, State 1, Procedure archive, Line 4 [Batch Start Line 0]
Invalid object name 'oldTable'.
Looks like name oldTable was stored somewhere and is used here by some kind of reference. It happens on both ssms and raw php+sql when trying to update.
Anyone have any idea?

Renaming a table will not update any Triggers that have been defined for the table (or any references to it anywhere else) so you need to manually update any triggers or other dependencies to reflect the new name.

Related

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

View Statement on SQL Server returns "Invalid Object Name"

When executing the following script on my SQL Server:
CREATE VIEW joiny AS
SELECT EventTime
FROM [dbo].[Table_1]
I get the following error:
Invalid object name 'Table_1'.
I cannot figure out why this is an error. Could anyone point me in the right direction? I tried with and without the [] as well as the "dbo".
This error can mean that the table [dbo].[Table_1] simply does not exist in the database you are using.
CREATE VIEW tabtest
AS
SELECT *
FROM dbo.TabTest
Results in:
Msg 208, Level 16, State 1, Procedure tabtest, Line 4 Invalid object
name 'dbo.TabTest'.
Because I do not have a table named dbo.tabtest in my database.\
If you are trying to create a view in a different database than the one where your table exists, then you need to use 3-part naming when you specify the table, like this:
CREATE VIEW joiny AS
SELECT EventTime
FROM [MyDatabaseName].[dbo].[Table_1]

SQL: Why does a CREATE TRIGGER need to be preceded by GO

When making a SQL script to create a trigger on a table, I wanted to check that the trigger doesn't already exist before I create it. Otherwise the script cannot be run multiple times.
So I added a statement to first check whether the trigger exists. After adding that statement, the CREATE TRIGGER statement no longer works.
IF NOT EXISTS (SELECT name FROM sysobjects
WHERE name = 'tr_MyTable1_INSERT' AND type = 'TR')
BEGIN
CREATE TRIGGER tr_MyTable1_INSERT
ON MyTable1
AFTER INSERT
AS
BEGIN
...
END
END
GO
This gives:
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'TRIGGER'.
The solution would be to drop the existing trigger and then create the new one:
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'tr_MyTable1_INSERT' AND type = 'TR')
DROP TRIGGER tr_MyTable1_INSERT
GO
CREATE TRIGGER tr_MyTable1_INSERT
ON MyTable1
AFTER INSERT
AS
BEGIN
...
END
GO
My question is: why is the first example failing? What is so wrong with checking the trigger exists?
Certain statements need to be the first in a batch (as in, group of statements separated by GO ).
Quote:
CREATE DEFAULT, CREATE FUNCTION, CREATE PROCEDURE, CREATE RULE, CREATE SCHEMA, CREATE TRIGGER, and CREATE VIEW statements cannot be combined with other statements in a batch. The CREATE statement must start the batch. All other statements that follow in that batch will be interpreted as part of the definition of the first CREATE statement.
It's simply one of the rules for SQL Server batches (see):
http://msdn.microsoft.com/en-us/library/ms175502.aspx
Otherwise you could change an object, say a table, and then refer to the change in the same batch, before the change was actually made.
Schema changes should always be seperate batch calls...I am guessing they do it to gaurantee your SELECT will succeed, if you modify schema in the same batch they may not be able to gaurantee that. Just a guess...

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