Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make ALTER COLUMN idempotent?

Tags:

sql-server

I have a migration script with the following statement:

ALTER TABLE [Tasks] ALTER COLUMN [SortOrder] int NOT NULL
  1. What will happen if I run that twice? Will it change anything the second time? MS SQL Management Studio just reports "Command(s) completed successfully", but with no details on whether they actually did anything.

  2. If it's not already idempotent, how do I make it so?

like image 814
Tomas Aschan Avatar asked Nov 10 '15 13:11

Tomas Aschan


People also ask

How do I make my database idempotent?

A common way to make your data pipeline idempotent is to use the delete-write pattern. As the name implies, the pipeline will first delete the existing data before writing new data. Be very careful to only delete data that the data pipeline will re-create .

What is idempotent script?

A script is idempotent when its repeated execution always leads to the same result. Whether it's the first or thirtieth run, it should "just work". This approach seems logical, but not every script follows it.

Is SQL insert idempotent?

INSERTs are idempotent. Deduplication parameters are controlled by merge_tree server settings.

How do you modify a column?

To modify column width:Position the mouse over the column line in the column heading so the cursor becomes a double arrow. Click and drag the mouse to increase or decrease the column width. Release the mouse. The column width will be changed.


2 Answers

I would say that second time, SQL Server checks metadata and do nothing because nothing has changed.

But if you don't like possibility of multiple execution you can add simple condition to your script:

CREATE TABLE Tasks(SortOrder VARCHAR(100));

IF NOT EXISTS (SELECT 1
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE [TABLE_NAME] = 'Tasks'
                 AND [COLUMN_NAME] = 'SortOrder'
                 AND IS_NULLABLE = 'NO'
                 AND DATA_TYPE = 'INT')
BEGIN 
  ALTER TABLE [Tasks] ALTER COLUMN [SortOrder] INT NOT NULL
END

SqlFiddleDemo

like image 111
Lukasz Szozda Avatar answered Oct 19 '22 20:10

Lukasz Szozda


  1. When you execute it the second time, the query gets executed but since the table is already altered, there is no effect. So it makes no effect on the table.

  2. No change is there when the script executes twice.

Here is a good MSDN read about: Inside ALTER TABLE

Let's look at what SQL Server does internally when performing an ALTER TABLE command. SQL Server can carry out an ALTER TABLE command in any of three ways:

  1. SQL Server might need to change only metadata.
  2. SQL Server might need to examine all the existing data to make sure it's compatible with the change but then change only metadata.
  3. SQL Server might need to physically change every row.
like image 36
Rahul Tripathi Avatar answered Oct 19 '22 20:10

Rahul Tripathi