我的表格如下:
项
我想编写SQL命令,它只会更新这些非空的值
我想做的伪代码:
UPDATE Items
SET
IF @NewName IS NOT NULL
{
Items.Name = @NewName
}
IF @NewDate IS NOT NULL
{
Items.Date = @NewDate
}
IF @newValue IS NOT NULL
{
Items.Valie = @NewValue
}
WHERE Items.ID = @ID
是否可以像这样编写查询?
答案 0 :(得分:2)
UPDATE Items
SET Name = ISNULL(@NewName,Name),
[Date] = ISNULL(@NewDate,[Date]),
Value = ISNULL(@NewValue,Value)
WHERE ID = @ID
答案 1 :(得分:0)
您无法在更新中使用if语句,您可以在条件
下使用以下查询进行更新'UPDATE Items
SET
Items.Name = (case when @NewName is not null then @NewName else end) ,
Items.Date = (case when @NewDate is not null then @newDate else end ),
Items.Valie = (case when @Valie is not null then @Valie else end )
WHERE Items.ID = @ ID'
答案 2 :(得分:-2)
你可以做这样的事情:
declare @sql varchar(1000)
set @sql = 'UPDATE Items SET '
IF @NewName IS NOT NULL
@sql = @sql + 'Items.Name = ' + @NewName
IF @NewDate IS NOT NULL
@sql = @sql + 'Items.Date = ' + @NewDate
IF @newValue IS NOT NULL
@sql = @sql + 'Items.Valie = ' + @NewValue
@sql = @sql + 'WHERE Items.ID = ' + @ID
exec(@sql)