ALTER PROCEDURE [dbo].[GetValues]
@FieldName NVARCHAR(50),
@FormName NVARCHAR(50),
@PoolName NVARCHAR(50)
AS SELECT FieldValue FROM [dbo].[Values]
INNER JOIN [dbo].[Fields]
ON [dbo].[Fields].FieldID = [dbo].[Values].FieldID
INNER JOIN [dbo].[FormFields]
ON [dbo].[FormFields].FieldID = [dbo].[Fields].FieldID
INNER JOIN [dbo].[Forms]
ON [dbo].[Forms].FormID = [dbo].[FormFields].FormID
INNER JOIN [dbo].[Pools]
ON [dbo].[Pools].FormID = [dbo].[Forms].FormID
WHERE [dbo].[Fields].FieldName = @FieldName
AND [dbo].[Forms].FormName = @FormName
AND [dbo].[Pools].PoolName = @PoolName
I expected this code to filter the Values by Field, Form and Pool names. But it only filters by the Field name. What’s wrong?
Forms
FormID FormName
96 FormA
98 FormB
97 FormC
Pools
PoolID FormID PoolName
29 96 PoolA1
31 98 PoolB1
30 97 PoolC1
Records
RecordID PoolID
42 29
43 29
44 29
45 31
46 31
47 31
Values
FieldID RecordID FieldValue
101 42 Yellow
101 43 Yellow
101 44 Yellow
101 45 Pink
101 46 Pink
101 47 Pink
102 42 Smith
102 43 Jones
102 44 Fletchers
103 42 Fred
103 43 Bob
103 44 Marty
For example, if I filter with “Favorite color” (FieldID=101), “FormA” (FormID=96) and “PoolA1” (PoolID=29), it shows “Yellow,Yellow,Yellow,Pink,Pink,Pink” whereas it should be “Yellow,Yellow,Yellow”.
As I thought, the problem was in the stored procedure itself. Everything else was fine. The JOINs were incorrectly done and that’s the reason why I got erroneous results. Here’s the solution: