我有三张桌子 1.主表M_MasterTable 2. M_MasterTable的详细信息表 3.实际物理表
如何通过将物理列与fieldname(2)匹配来获得旋转结果,从而编写一个可以提供输出的查询?
Id是主键 详细是外键。
1:
答案 0 :(得分:1)
看看这个:
--Quick and Dirty Sample Data
DECLARE @master TABLE
(
id INT,
tablename NVARCHAR(100)
)
DECLARE @detail TABLE
(
detailid INT,
tableid INT,
fieldname NVARCHAR(100),
excelmappingcolumn NVARCHAR(100)
)
INSERT INTO @master VALUES (1,N'A')
INSERT INTO @detail VALUES (1,1,N'Code',N'VirtualCode')
INSERT INTO @detail VALUES (2,1,N'Value',N'Value of Virtual Exam')
-- Getting the query
DECLARE @stmt NVARCHAR(MAX) = ''
DECLARE @columns NVARCHAR(MAX)
SELECT @columns = COALESCE(@columns + ',[','',@columns + ',[') + fieldname + '] AS [' + excelmappingcolumn + ']'
FROM @detail WHERE tableid = 1
SELECT @stmt = 'SELECT ' + @columns + ' FROM ' + tablename
FROM @master m
WHERE m.id = 1
PRINT @stmt
--Execute
EXEC sp_executesql @stmt