假设我有一个变量:
declare @x int = /* smth here */
我有一个带有列(例如ColX
)的表,它not null
有一个default
约束。现在我想以这样的方式更新表中的一些行:
update MyTable
set ColX = isnull(@x, default)
where blah-blah-blah
显然它无法执行,因为 sql-server 会显示错误,但我认为这个示例清楚地反映了我想要做的事情。所以问题是如何做到这一点?
谢谢!
更新 所以我现在有这些方法:
- 通过系统视图执行此操作 - 获取 column_default 属性并使用动态查询执行
在单独的子查询中执行这两种情况:
if @x is null then update /* use default */ else update /* use @x */
这种方式是直接且最简单的。对于其他会进一步阅读它的人来说,甚至可能是最透明的。还要记住,它还需要为两者分别插入
@x is null /* use default */
和
@x is not null /* use @x */
案例
创建用户定义函数:
create function GetValueForColX(@value int) returns int as begin return isnull(@value, /* default value */) end
然后在默认情况下使用它 -
(GetValueForColX(null))
并在插入/更新查询中使用GetValueForColX(@x)