根据另一个表的值选择表和字段

时间:2015-07-09 12:23:11

标签: sql-server

是否可以从表中加入并选择一个字段,其中表和字段名称作为文本存储在另一个表中?

假设我有TableofValues,TableA,TableB和TableC表,如下所示。

是否可以基于TableofValues中的TableName加入相关表,然后根据FieldName选择字段,其中TableRowID =连接表中的ID?

这是SQL Server 2008。

表格的示例集:

enter image description here

期望的结果:

enter image description here

3 个答案:

答案 0 :(得分:1)

您也可以在没有动态查询的情况下实现此目的。请参阅以下代码:

-- Create Demo Data
CREATE TABLE #TableOfValues(id int identity(1,1), value float, TableName nvarchar(30), FieldName nvarchar(30), TableRowId int)

INSERT INTO #TableOfValues(value, TableName, FieldName, TableRowId)
VALUES  (1234.2,N'TableA',N'Customer',1),
        (245.5,N'TableB',N'Cust',3),
        (248.59,N'TableA',N'Customer',2),
        (8526.36,N'TableC',N'Cstmer',1),
        (224.15,N'TableB',N'Cust',5),
        (148.98,N'TableC',N'Cstmer',2)

CREATE TABLE #TableA(id int identity(1,1), Customer nvarchar(30))

INSERT INTO #TableA(Customer) 
VALUES(N'Bloggs'),(N'Smith'),(N'Jones')

CREATE TABLE #TableB(id int identity(1,1), Cust nvarchar(30))

INSERT INTO #TableB(Cust)
VALUES (N'Aother'),(N'NJONES'), (N'FBLOGGS'), (N'SMITH'), (N'BARTHUR')

CREATE TABLE #TableC(id int identity(1,1), Cstmer nvarchar(30))

INSERT INTO #TableC(Cstmer)
VALUES(N'Mr Fred Bloggs'),(N'Tony Smith')

-- Your Part
SELECT tov.id, tov.value, tov.TableName, tov.FieldName, tov.TableRowId, tabs.tabVal
FROM #TableOfValues as tov
INNER JOIN (
    SELECT N'TableA' as tabName, a.id, a.Customer as tabVal
    FROM #TableA as a
    UNION ALL
    SELECT N'TableB' as tabName, b.id, b.Cust as tabVal
    FROM #TableB as b
    UNION ALL
    SELECT N'TableC' as tabName, c.id, c.Cstmer as tabVal
    FROM #TableC as c
) as tabs
    ON tov.TableName = tabs.tabName
    AND tov.TableRowId = tabs.id

-- Cleanup
DROP TABLE #TableOfValues
DROP TABLE #TableA
DROP TABLE #TableB
DROP TABLE #TableC

如果需要,您可以添加(如果他们不会出现)索引到表格。如果您寻求特定值,这些将进一步提高查询性能。

CREATE CLUSTERED INDEX [NCI_TableOfValues_id]
ON #TableOfValues ([id])

CREATE CLUSTERED INDEX [NCI_TableA_id]
ON #TableA ([id])

CREATE CLUSTERED INDEX [NCI_TableB_id]
ON #TableB ([id])

CREATE CLUSTERED INDEX [NCI_TableC_id]
ON #TableC ([id])

CREATE NONCLUSTERED INDEX [NCI_TableOfValues_TableName]
ON #TableOfValues([TableName])
INCLUDE ([id],[value],[FieldName],[TableRowId])

除了解决方案,桌面设计有点糟糕。它会进一步提高您的SELECT效果。

答案 1 :(得分:0)

除了你应该有一个非常好的理由,因为它是非常糟糕的设计,否则你可以想到使用SchemaBinding的VIEW。

您必须为任何给定的TableName创建一个VIEW。这可以在JOIN中使用

答案 2 :(得分:0)

您也可以这样做。您希望合并#TableA#TableB#TableC中的所有行,并添加一列以确定FieldName

SELECT
    Customer = FieldValue,
    Value = v.value
FROM #TableOfValues v
LEFT JOIN (
    SELECT id, Customer AS FieldValue, 'Customer' AS FieldName FROM #TableA UNION ALL
    SELECT id, Cust, 'Cust' FROM #TableB UNION ALL
    SELECT id, Cstmer, 'Cst' FROM #TableC
)t
    ON v.FieldName = t.FieldName
    AND v.TableRowId = t.id