6

lets say I have a script like that:

if(some condition) begin select somecolumn from sometable end

Lets say, that "somecolumn" does not exist and the condition is not true, which means the select is NOT executed. Even though the select would not be executed, the script is not valid, Management Studio complains about the missing column "somecolumn".

Question: Can I somehow disable this sort of check so that the script is executed and since the if is not true, it will never notice that the column is missing?

Thanks :-)

1
  • There is something seriously wrong with your design if you have to worry about whether a column exists or not. Commented Mar 30, 2010 at 17:19

2 Answers 2

5

Use dynamic SQL

if(some condition)
begin
    exec ('select somecolumn from sometable') --or sp_executesql
end

It actually makes no sense to run this because of what SQL is. It's not executed line by line: the whole batch is parsed etc in one go and the error is generated here, before anything actually runs in the sense you mean. This is by design...

Sign up to request clarification or add additional context in comments.

1 Comment

not 100% This code works for me: IF OBJECT_ID('Reports.dbo.RecordsTable') IS NULL However other approaches with just plain parameter strings to indicate table1 or 2 fail. However the dynamic sql trick always works, but is a bit annoying of course.
2

You can create a procedure that references a table that does not exist however that is the only exception to the rule. From the BOL:

Deferred name resolution can only be used when you reference nonexistent table objects. All other objects must exist at the time the stored procedure is created. For example, when you reference an existing table in a stored procedure you cannot list nonexistent columns for that table.

Beyond using dynamic SQL, there is no means to reference non-existent columns in a stored procedure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.