1

I need to update some columns in my table row. For this I write a stored procedure and there is key code below. I want to check that @Title or @Descriptions are not NULL and in this case update this data. What is a best practice for such situations?

UPDATE configuration
SET Title = @Title,
    Description = @Description, 
    ShowHeader = @ShowHeader,
    XmlConfiguration = @XmlConfiguration
WHERE Id = @Id

EDIT:

Let's imagine that the Title is not null but description is null. In this case I want to update only title and save the description without changes. Is it possible?

4

3 回答 3

3
UPDATE configuration
SET Title = @Title,
    Description = @Description, 
    ShowHeader = @ShowHeader,
    XmlConfiguration = @XmlConfiguration
WHERE Id = @Id
AND (@Title IS NOT NULL OR @Descriptions IS NOT NULL)

对于新要求:

UPDATE configuration
SET Title = @Title,
    Description = ISNULL(@Description,Description), 
    ShowHeader = ISNULL(@ShowHeader,ShowHeader),
    XmlConfiguration = @XmlConfiguration
WHERE Id = @Id
AND (@Title IS NOT NULL OR @Descriptions IS NOT NULL)
于 2013-09-16T19:05:15.420 回答
1
UPDATE configuration
SET Title = ISNULL(@Title,Title),
    Description = ISNULL(@Description,Description), 
    ShowHeader = @ShowHeader,
    XmlConfiguration = @XmlConfiguration
WHERE Id = @Id

我想检查标题是否不为空,然后更新标题,与描述的想法相同。

如果我理解正确,则仅当传递的值不为空时,您才希望将标题列设置为参数的值,并且对描述列执行类似的操作。

上面的代码会做到这一点。如果@Title 和@Descriptions 都为null,则对应的两个列中的值不会改变,但其他列仍会更新。如果@Title 和@Descriptions 都为空,PM 77-1 和 Lamak 的答案将根本不执行任何更新。

请注意,这些值不会改变;然而,更新语句实际上将写入列(即当前值)。就数据完整性而言,这没有什么区别,但在审计或变更跟踪考虑方面可能很重要。

如果您不想在两个参数都为空时执行更新,您可以添加如下条件:

IF @Title IS NOT NULL OR @Descriptions IS NOT NULL
BEGIN
    UPDATE configuration
    SET Title = ISNULL(@Title,Title),
        Description = ISNULL(@Description,Description), 
        ShowHeader = @ShowHeader,
        XmlConfiguration = @XmlConfiguration
    WHERE Id = @Id
END

使用 if 块将强制服务器首先评估您的两个参数条件。如果将它们放在 where 子句中,则服务器可能(尽管不太可能)决定首先检查 @Id 条件。上面的代码在@Title 和@Descriptions 都为空的情况下保存了潜在的索引查找。然而,这充其量只是很小的节省。

于 2013-09-16T19:16:00.420 回答
0

你也可以试试这个“技巧”。

如果更新值为 null,则使用 ~original~ 值。

Use Northwind
GO


 declare @City varchar(12)
  select @City = null

 Update [dbo].[Customers]
 Set
    [City] = ISNULL(@City, custs.City)
From
[dbo].[Customers] custs

where CustomerID = 'WOLZA'

Select City as MyCity, * from [dbo].[Customers] where CustomerID = 'WOLZA'


  select @City = 'WarszawaABC'

 Update [dbo].[Customers]
 Set
    [City] = ISNULL(@City, custs.City)
From
[dbo].[Customers] custs

where CustomerID = 'WOLZA'

Select City as MyCity, * from [dbo].[Customers] where CustomerID = 'WOLZA'
于 2013-09-16T19:24:00.193 回答