使用查找中的值替换查询中的列名称

时间:2014-08-22 15:03:37

标签: sql join view

我在SQL Express数据库中工作,其中包含几个类似于以下内容的表...

Table 1包含一系列数据,其列名反映用户输入表单上的控件类型 - 如下所示......

ID, Text1, Text2, Combo1, Combo2, Num1, Num2  
1, "DP01", "WASW", "John Smith", "123 Maple St", 12, 576  
2, "DP02", "WABW", "Jane Smith", "234 River Dr", 23, 34  
3, "DP03", "WADM", "James Smith", "567 Dump Rd", 3, 986  
4, "DP04", "WARV", "Joe Smith", "678 Main St", 59, 124  

Table 2包含一些元数据,包括表1中引用的字段的标题。类似于......

ID, FieldName, Title  
1, Text1, PermitNumber  
2, Text2, FCode  
3, Combo1, OwnerName  
4, Combo2, Address  
5, Num1, OwnerID  
6, Num2, AddressID  

我没有设计或创建数据库,但这是我必须使用的。

我希望能够使用表2中的标题值来查询表1中的数据。我希望这可以通过使用连接和创建视图来完成,但我不确定是什么语法就是这样做的。最终,我希望展示的观点是......

ID, PermitNumber, FCode, OwnerName, Address, OwnerID, AddressID  
1, "DP01", "WASW", "John Smith", "123 Maple St", 12, 576  
2, "DP02", "WABW", "Jane Smith", "234 River Dr", 23, 34  
3, "DP03", "WADM", "James Smith", "567 Dump Rd", 3, 986  
4, "DP04", "WARV", "Joe Smith", "678 Main St", 59, 124  

这可能吗?

我希望有人可以提供帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用游标或一段时间来构建动态SQL:

DECLARE @fieldName varchar(32), @title varchar(32)
DECLARE @sql_cmd varchar(512)
SET @sql_cmd='SELECT '

DECLARE sql_cursor CURSOR FOR
SELECT FieldName, Title FROM table_2 ORDER BY ID

OPEN sql_cursor

FETCH NEXT FROM sql_cursor INTO @fieldName, @Title

WHILE (@@FETCH_STATUS = 0)
BEGIN
    SET @sql_cmd = @sql_cmd + @fieldName + ' AS ' + @Title + ', '

    FETCH NEXT FROM sql_cursor
    INTO @fieldName, @Title
END;

CLOSE sql_cursor
DEALLOCATE sql_cursor

SET @sql_cmd = SUBSTRING(@sql_cmd,0,LEN(@sql_cmd)-2) + ' FROM table_1'
EXEC(@sql_cmd)

答案 1 :(得分:0)

UNPIVOT应用于Table 1。这会给你:

1, Text1, "DP01"
1, Text2, "WASW"
1, Combo1, "John Smith"
1, Combo2, "123 Maple St"
...
4, Num1, 59
4, Num2, 124

将此加入Table 2以获取

1, Text1, "DP01", PermitNumber  
1, Text2, "WASW", FCode
1, Combo1, "John Smith", OwnerName
1, Combo2, "123 Maple St", Address
...
4, Num1, 59, OwnerID
4, Num2, 124, AddressID

最后PIVOT省略了Table1中的列名称,您将获得所需的格式。