How can I alter this computed column in SQL Server 2008?

耗尽温柔 提交于 2019-11-28 01:47:04

If you're trying to change an existing column, you can't use ADD. Instead, try this:

alter table tbPedidos alter column restricoes as (cast(case when restricaoLicenca = 1 or restricaoLote = 1 or restricaoValor = 1 then 1 else 0 end as bit))

EDIT: The above is incorrect. When altering a computed column the only thing you can do is drop it and re-add it.

Something like this:

ALTER TABLE dbo.MyTable
DROP COLUMN OldComputedColumn

ALTER TABLE dbo.MyTable
ADD OldComputedColumn AS OtherColumn + 10

Source

This is one of those situations where it can be easier and faster to just use the diagram feature of SQL Server Management Studio.

  1. Create a new diagram, add your table, and choose to show the formula column in the diagram's table view.
  2. Change the columns formula to an empty string ('') or something equally innocuous (probably such that you don't change the column's datatype).
  3. Save the diagram (which should save the table).
  4. Alter your function.
  5. Put the function back in the formula for that column.
  6. Save once again.

Doing it this way in SSMS will retain the ordering of the columns in your table, which a simple drop...add will not guarantee. This may be important to some.

Amicable

As Michael Todd correctly states in his answer

When altering a computed column the only thing you can do is drop it and re-add it.

Just had to do this myself, although I wanted to preserve the existing data (as Management Studio does when you perform this task through the designer).

My solution was to store the data in a temporary table then update the table with the stored values after I'd dropped and recreated the calculated column.

SELECT IDKey, Value
INTO #Temp
FROM MyTable

ALTER TABLE MyTable
DROP COLUMN Value

ALTER TABLE MyTable
ADD Value nvarchar(max) NULL

UPDATE MyTable
SET Value = #Temp.Value
FROM
MyTable
INNER JOIN #Temp ON #Temp.IDKey= MyTable.IDkey
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!