Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL error stating invalid column name when I have verification if it exists. Why?

Tags:

sql

database

tsql

There is staging script, which creates new column DOCUMENT_DEFINITION_ID stages it with values of MESSAGE_TYPE_ID + 5 and then removes column MESSAGE_TYPE_ID.

First time everything run ok, but when I run script second time I'm getting this error:

Invalid column name 'MESSAGE_TYPE_ID'.

It makes no sense since, I have verification if that column exists.

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'MESSAGE_TYPE_ID' AND TABLE_NAME = 'DOCUMENT_QUEUE')
BEGIN
  UPDATE DOCUMENT_QUEUE SET DOCUMENT_DEFINITION_ID = MESSAGE_TYPE_ID + 5 --Error here.. but condition is not met

Why?

like image 323
Andriy Buday Avatar asked Oct 11 '10 11:10

Andriy Buday


People also ask

How do I solve the ambiguous name column error in SQL?

You may see an error that says something like Column 'id' in field list is ambiguous . This error means that there is a field name that is present in more than one table, so it needs to be scoped with the table name to avoid ambiguity: using orders.id instead of just id will resolve the issue.

What are valid column names in SQL?

Column names must contain only A to Z, 0 to 9, and underscore (_) characters. Column names can contain multiple underscores. The column name must not be very generic. Avoid words such as term, multiplier, description, name, code, and so on.

What causes SQL error?

The cause of these problems can vary from file system corruption, underlying hardware system issues, driver issues, corrupted pages in memory, or problems with the SQL Server Engine. Refer to the Investigate root cause section on how to find the cause of errors that are reported.


1 Answers

Try this

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'MESSAGE_TYPE_ID' AND TABLE_NAME = 'DOCUMENT_QUEUE')
BEGIN
   EXEC( 'UPDATE DOCUMENT_QUEUE SET DOCUMENT_DEFINITION_ID = MESSAGE_TYPE_ID + 5 ')
END

It bypasses the delayed name resolution by wrapping the update in dynamic statement.

like image 63
no_one Avatar answered Oct 19 '22 12:10

no_one