我有3張桌子。我該如何重構重複的SQL更新查詢?
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'