如何重构重复的SQL更新查询?

时间:2009-07-17 07:35:36

标签: sql sql-server tsql refactoring

我有3张桌子。

1. Users 4 Cols
UserID - User - RealName - Flags

2. UsersGroups 2 Cols
UserID - GroupID

3. Groups 3 Cols
GroupID - Group - Flags

我希望在User表上为User = 'Administrator'设置标记并将其应用于Group表。

我有以下SQL可行,但我也有几个标志,我必须使用按位运算符。

我发现我的代码非常重复,所以想知道是否有人会建议一些不会影响性能的重构。

代码:

--- SET FLAG 1      
UPDATE User
SET User.Flags = User.Flags | 2048
WHERE User.Value = 'Administrator'

UPDATE dbo.Group
SET dbo.Group.Flags = 
    (Select e.Flags FROM dbo.User p INNER JOIN dbo.UserInGroup pe ON p.UserID = pe.UserID
    INNER JOIN dbo.Group e ON e.GroupID = pe.GroupID
    WHERE p.Value = 'Administrator') | 2048

FROM dbo.User p INNER JOIN dbo.UserInGroup pe ON p.UserID = pe.UserID
INNER JOIN dbo.Group e ON e.GroupID = pe.GroupID
WHERE p.Value = 'Administrator'

-- SET FLAG 2       
UPDATE User
SET User.Flags = User.Flags | 512
WHERE User.Value = 'Administrator'

UPDATE dbo.Group
SET dbo.Group.Flags = 
    (Select e.Flags FROM dbo.User p INNER JOIN dbo.UserInGroup pe ON p.UserID = pe.UserID
    INNER JOIN dbo.Group e ON e.GroupID = pe.GroupID
    WHERE p.Value = 'Administrator') | 512

FROM dbo.User p INNER JOIN dbo.UserInGroup pe ON p.UserID = pe.UserID
INNER JOIN dbo.Group e ON e.GroupID = pe.GroupID
WHERE p.Value = 'Administrator'

1 个答案:

答案 0 :(得分:1)

您可以创建一个存储过程,它将标志位值和用户/组名称作为参数,并将它们用作查询的参数 - 然后在需要更改标志时调用存储过程

像(未经测试的)

create proc usp_set_flags
    @flag int
    ,@username varchar(50)
AS
UPDATE User
SET User.Flags = User.Flags | @flag 
WHERE User.Value = @username 

UPDATE dbo.Group
SET dbo.Group.Flags = 
    (Select e.Flags FROM dbo.User p INNER JOIN dbo.UserInGroup pe ON p.UserID = pe.UserID
    INNER JOIN dbo.Group e ON e.GroupID = pe.GroupID
    WHERE p.Value =  @username) | @flag

FROM dbo.User p INNER JOIN dbo.UserInGroup pe ON p.UserID = pe.UserID
INNER JOIN dbo.Group e ON e.GroupID = pe.GroupID
WHERE p.Value =  @username
GO

(这是一个不同的基本示例 - 添加一些验证和错误检查是个好主意。)

然后你会这样称呼它:

exec usp_set_flags @flag = 2048, @username = 'Administrator'