如何更新 table 并忽略已计算的计算列,但如果未计算则更新它
How to update a table and ignore a computed column if it is computed but update it if it is not computed
我有不同版本的 SQL 服务器数据库:
- 在
DB 1
中,列 'IsReadOnly' 是计算列
- 在
DB 2
中,列 'IsReadOnly' 是非计算列
我需要创建一个适用于两个版本的标准脚本:
IF EXISTS (SELECT 1 FROM sys.columns
WHERE Name = N'IsReadOnly'
AND Object_ID = OBJECT_ID(N'dbo.TableA')
AND is_computed = 0)
BEGIN
UPDATE TableA
SET IsReadOnly = @IsReadOnly
WHERE Id = @ID
END
当 运行 以上时,它适用于 is_computed = 0 的版本。但是当 运行 在 is_computed = 1 的版本上时,我得到:
Msg 271, Level 16, State 1, Line 322
The column "IsReadOnly" cannot be modified because it is either a computed column or is the result of a UNION operator
非常感谢任何帮助。谢谢
这是一个 compile-time 与 execution-time 的问题。错误发生在无法更新值的数据库 compile-time 处。
您可以使用动态 SQL:
绕过它
IF EXISTS( SELECT 1 FROM sys.columns
WHERE Name = N'IsReadOnly'
AND Object_ID = Object_ID(N'dbo.TableA')
AND is_computed = 0
)
BEGIN
EXEC sp_execute_sql N'
Update TableA
Set IsReadOnly = @IsReadOnly
Where Id = @ID',
N'@IsReadOnly int, @ID int', -- guessing at the types
@IsReadOnly=@IsReadOnly, @ID=@ID;
END
不过,更简单的方法可能是 TRY
/CATCH
块:
BEGIN TRY
Update TableA
Set IsReadOnly = @IsReadOnly
Where Id = @ID ;
END TRY
BEGIN CATCH
-- Check for the particular error and do something when that occurs
END CATCH;
我有不同版本的 SQL 服务器数据库:
- 在
DB 1
中,列 'IsReadOnly' 是计算列 - 在
DB 2
中,列 'IsReadOnly' 是非计算列
我需要创建一个适用于两个版本的标准脚本:
IF EXISTS (SELECT 1 FROM sys.columns
WHERE Name = N'IsReadOnly'
AND Object_ID = OBJECT_ID(N'dbo.TableA')
AND is_computed = 0)
BEGIN
UPDATE TableA
SET IsReadOnly = @IsReadOnly
WHERE Id = @ID
END
当 运行 以上时,它适用于 is_computed = 0 的版本。但是当 运行 在 is_computed = 1 的版本上时,我得到:
Msg 271, Level 16, State 1, Line 322
The column "IsReadOnly" cannot be modified because it is either a computed column or is the result of a UNION operator
非常感谢任何帮助。谢谢
这是一个 compile-time 与 execution-time 的问题。错误发生在无法更新值的数据库 compile-time 处。
您可以使用动态 SQL:
绕过它IF EXISTS( SELECT 1 FROM sys.columns
WHERE Name = N'IsReadOnly'
AND Object_ID = Object_ID(N'dbo.TableA')
AND is_computed = 0
)
BEGIN
EXEC sp_execute_sql N'
Update TableA
Set IsReadOnly = @IsReadOnly
Where Id = @ID',
N'@IsReadOnly int, @ID int', -- guessing at the types
@IsReadOnly=@IsReadOnly, @ID=@ID;
END
不过,更简单的方法可能是 TRY
/CATCH
块:
BEGIN TRY
Update TableA
Set IsReadOnly = @IsReadOnly
Where Id = @ID ;
END TRY
BEGIN CATCH
-- Check for the particular error and do something when that occurs
END CATCH;