I’m new to SQLServer scripting (normally being a C++ developer), and would really appreciate a bit of assistance.
I am attempting to perform a “find and replace” update on all tables in a SQLServer database that contain a ‘PROJID’ column. I am really struggling to find a way to do this that doesn’t report to me:
Msg 207, Level 16, State 1, Line 1 Invalid column name ‘PROJID’.
The statement I am executing is:
EXEC
(
'IF EXISTS(SELECT * FROM sys.columns WHERE name = N''PROJID'' AND Object_ID = Object_ID(N''' + @TableName + '''))' +
' BEGIN' +
' UPDATE ' + @TableName +
' SET ' + @ColumnName + ' = REPLACE(' + @ColumnName + ',''' + @ReplaceIDStr + ''',''' + @FindIDStr + ''')' +
' WHERE ' + @ColumnName + ' LIKE ''' + @ReplaceIDStr + '''' + ' AND PROJID = ''1000''' +
' END'
)
I have also tried using:
'IF COL_LENGTH(''' + @TableName + ''',''PROJID'') IS NOT NULL' +
instead of the column-exist check above. This also still gives me the “Invalid Column Name” messages.
I would be happy to take the column-exist check outside of the ‘Exec’ statement, but I’m not sure how to go about doing this either.
Output the results of this query to text. Don’t forget to change the values of the variables! Take the result of this and run it.
EDIT: Also, some reasoning: You said you want update all tables where they contain a column called
PROJID. Your first query just says that if the table@TableNamehas aPROJIDcolumn, then update@ColumnNameon it. But it doesn’t guarantee that it has @ColumnName on it. The query I gave doesn’t check that either, because I’m assuming that all tables that havePROJIDalso have@ColumnName. If that isn’t the case, let me know and I can update the answer to check that. That you’re getting anInvalid Column Nameerror points to@ColumnNamenot existing.Your query would have updated one table (
@TableName) at most, whereas the one I gave you will update every table that hasPROJID. I hope that’s what your going for.EDIT 2: Here is a version that would run it all at once: