我有一個表名稱/值對的記錄,我需要確認值存在針對查找每個名稱SQL查詢校驗值在查找存在基於另一個列值
KEYVAL - NameValue對錶
| MyID1 | MyRecNumber | MyFieldName | MyFieldValue |
|-------|-------------|-------------|--------------|
| 1 | 1 | FirstField | One |
| 2 | 1 | SecondField | Car |
| 3 | 2 | FirstField | Two |
| 4 | 2 | SecondField | Firetruck |
| 5 | 3 | FirstField | Blue |
| 6 | 3 | SecondField | Car |
LookupTable中 - 表匹配(從KEYVAL)與LookupValue名稱值(CheckVals表)
| MyID2 | MyFieldName | LookupName |
|-------|-------------|------------|
| 1 | FirstField | FieldOne |
| 2 | SecondField | FieldTwo |
CheckVals - 表有效值每個字段
| MyID3 | LookupFieldName | LookupValue |
|-------|-----------------|-------------|
| 1 | FieldOne | One |
| 2 | FieldOne | Two |
| 3 | FieldOne | Three |
| 4 | FieldTwo | Car |
| 5 | FieldTwo | Truck |
| 6 | FieldTwo | Bus |
我有一個查詢,將檢查針對單個名稱查找值,但我不確定如何使這項檢查所有的名字對查找表。在此查詢中,它繞過LookupTable
,因爲我在查詢本身中指定了查找值。
DECLARE @AttributeName AS VARCHAR(50)
DECLARE @Lookup AS VARCHAR(50)
SET @AttributeName = 'SecondField'
SET @Lookup = 'FieldTwo';
SELECT
MyRecNumber,
MyFieldName,
MyFieldValue
FROM
dbo.KeyVal kv
WHERE
MyFieldName = @AttributeName
AND MyFieldValue NOT IN
(
SELECT
LookupValue
FROM
dbo.CheckVals cv
WHERE cv.LookupFieldName = @Lookup
)
問:我如何才能做到對查找在KeyVal
表中的所有值,通過LookupTable
表,以檢查是否在MyFieldValue
的價值CheckVals
存在對MyFieldName
和LookupName
匹配?
這就是我希望能獲得 - 具有無效值查詢返回兩行結果
| MyRecNumber | MyFieldName | MyFieldValue |
|-------------|-------------|--------------|
| 2 | SecondField | Firetruck |
| 3 | FirstField | Blue |
示例表
CREATE TABLE [dbo].[KeyVal](
[MyID1] [smallint] IDENTITY(1,1) NOT NULL,
[MyRecNumber] [smallint] NULL,
[MyFieldName] [varchar](50) NULL,
[MyFieldValue] [varchar](50) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[LookupTable](
[MyID2] [smallint] IDENTITY(1,1) NOT NULL,
[MyFieldName] [varchar](50) NULL,
[LookupName] [varchar](50) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[CheckVals](
[MyID3] [smallint] IDENTITY(1,1) NOT NULL,
[LookupFieldName] [varchar](50) NULL,
[LookupValue] [varchar](50) NULL
) ON [PRIMARY]
樣本數據
INSERT INTO [dbo].[KeyVal]
([MyRecNumber], [MyFieldName], [MyFieldValue])
VALUES
(1, 'FirstField', 'One'),
(1, 'SecondField', 'Car'),
(2, 'FirstField', 'Two'),
(2, 'SecondField', 'Firetruck'),
(3, 'FirstField', 'Blue'),
(3, 'SecondField', 'Car')
INSERT INTO [dbo].[LookupTable]
([MyFieldName], [LookupName])
VALUES
('FirstField', 'FieldOne'),
('SecondField', 'FieldTwo')
INSERT INTO [dbo].[CheckVals]
([LookupFieldName], [LookupValue])
VALUES
('FieldOne', 'One'),
('FieldOne', 'Two'),
('FieldOne', 'Three'),
('FieldTwo', 'Car'),
('FieldTwo', 'Truck'),
('FieldTwo', 'Bus')
請編輯您的問題,並顯示你想得到的結果。 –