Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In this case you can avoid the problem by adding the column as <code>NOT NULL</code> and setting the values for existing rows in one statement <a href="https://stackoverflow.com/a/12472606/73226">as per my answer here</a>.</p> <p>More generally the problem is a parse/compile issue. SQL Server tries to compile all statements in the batch before executing any of the statements.</p> <p>When a statement references a table that doesn't exist at all the statement is subject to deferred compilation. When the table already exists it throws an error if you reference a non existing column. The best way round this is to do the DDL in a different batch from the DML. </p> <p>If a statement both references a non existing column in an existing table and a non existent table the error may or may not be thrown before compilation is deferred.</p> <p>You can either submit it in separate batches (e.g. by using the batch separator <code>GO</code> in the client tools) or perform it in a child scope that is compiled separately by using <code>EXEC</code> or <code>EXEC sp_executesql</code>. </p> <p>The first approach would require you to refactor your code as an <code>IF ...</code> cannot span batches.</p> <pre><code>IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = 'OPT_LOCK' AND object_ID = Object_id('REP_DSGN_SEC_GRP_LNK')) BEGIN ALTER TABLE REP_DSGN_SEC_GRP_LNK ADD OPT_LOCK NUMERIC(10, 0) EXEC('UPDATE REP_DSGN_SEC_GRP_LNK SET OPT_LOCK = 0'); ALTER TABLE REP_DSGN_SEC_GRP_LNK ALTER COLUMN OPT_LOCK NUMERIC(10, 0) NOT NULL END; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload