I have 2 tables which share a common table of “types”
The type table is as follows:
CREATE TABLE [ModifierType](
[ModifierTypeID] [int] NOT NULL,
[Code] [varchar](10) NOT NULL,
[Name] [varchar](50) NOT NULL,)
CREATE TABLE [UserRequest](
[UserRequestID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,)
CREATE TABLE [Matrix](
[MatrixID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,)
CREATE TABLE [UserRequestModifier](
[UserRequestModifierID] [int] NOT NULL,
[UserRequestID] [int] NOT NULL,
[ModifierTypeID] [int] NOT NULL,
[Value] [varchar](50) NOT NULL,)
CREATE TABLE [MatrixModifier](
[MatrixModifierID] [int] NOT NULL,
[MatrixID] [int] NOT NULL,
[ModifierTypeID] [int] NOT NULL,
[Value] [varchar](50) NOT NULL,)
The others are a UserRequestModifier table, and a “MatrixModifier” table which contains rules for determining access a request should be provisioned. Matrix in this case just refers to a set of rules that will grant access to a specific application or group. These two tables each have a ModifierTypeID which will link the two and a value field that will be used for finding matches.
However, each UserRequest/Matrix (parents to the modifier tables) can each have multiple modifier records.
What I need to do, is find all the Matrix records for which the UserRequestModifiers meets all the MatrixModifier requirements. Basically, I want to ignore any MatrixIDs that have even 1 modifier value that does not match ANY of the UserRequestModifier values.
So far I have a query that will do it, but it seems a bit backwards to me, because I’m having to first find all the MatrixIDs that the UserRequestModifiers do not meet the requirements in a subselect. Then getting the records that are NOT IN those results as follows:
SELECT
UR.[UserRequestModifierID]
,UR.[ModifierTypeID]
,UR.[Value] AS [URValue]
,MM.[Value] AS [MMValue]
,MM.[MatrixModifierID]
,MM.[MatrixID]
,MM.[ModifierTypeID]
,M.[MatrixID]
FROM
AMP.[UserRequestModifier] AS UR
LEFT OUTER JOIN AMP.[MatrixModifier] AS MM
ON (MM.[ModifierTypeID] = UR.[ModifierTypeID])
LEFT OUTER JOIN AMP.[Matrix] AS M
WHERE
UR.[UserRequestID] = @UserRequestID
AND M.[MatrixID] IS NOT NULL
AND M.[MatrixID] NOT IN
(SELECT
DISTINCT MM.[MatrixID]
FROM
AMP.[UserRequestModifier] AS UR
LEFT OUTER JOIN AMP.[MatrixModifier] AS MM
ON (MM.[ModifierTypeID] = UR.[ModifierTypeID])
WHERE
UR.[UserRequestID] = @UserRequestID
AND (CASE WHEN LTRIM(RTRIM(MM.[Value])) = LTRIM(RTRIM(UR.[Value])) THEN 1 ELSE 0 END) = 0
AND MM.[MatrixID] IS NOT NULL)
ORDER BY M.[MatrixID], MM.[ModifierTypeID]
I know this is a bit hard to follow, but I’m hoping someone can point out something obvious I’m missing.
For MS SQL Server: