对我来说有趣但很复杂,我有以下信息:
CREATE TABLE #mainTable (id INT, ename VARCHAR(20), eaddress VARCHAR(20))
INSERT INTO #mainTable VALUES
(1, 'A', 'B'),
(2, 'B', 'C'),
(3, 'C', 'D')
--OrgTable
id ename eaddress
1 A B
2 B C
3 C D
CREATE TABLE #mappingTable (ExportField VARCHAR(20), SelectField VARCHAR(20))
INSERT INTO #mappingTable VALUES
(1, 'ID'),
(2, 'EName'),
(3, 'EAddress')
--#mappingTable
ExportField SelectField
1 ID
2 EName
3 EAddress
CREATE TABLE #queryBlock(id INT, Equery VARCHAR(MAX))
INSERT INTO #queryBlock VALUES
(1, 'SELECT id AS [ID], ename AS [EName], eaddress AS [EAddress] FROM #mainTable')
我只需执行上面保存在Equery列中的查询,我无法直接进行更改,但输出将如下所示,新的列名或映射表中的标题。
--Desired Output
1 2 3
-------------
1 A B
2 B C
3 C D
我有几十个类似的映射任务,但一直想着从哪里开始。请帮帮我,真的,我将非常感谢你。
答案 0 :(得分:2)
使用以下查询。
DECLARE@colList varchar(500)
SELECT @colList=coalesce(@colList+ ',', '') + convert(varchar(12),SelectField)+' as '+QUOTENAME(cast(ExportField as varchar(10)))
FROM #mappingTable B
INSERT INTO #queryBlock VALUES
(1, 'SELECT '+ @colList+'FROM #mainTable')
如果您想动态执行它,请尝试编写如下脚本。
DECLARE @sql NVARCHAR(MAX)='SELECT '+ @colList+'FROM #mainTable'
EXEC(@sql)
如果您想从#quocketblock tabble运行它,请使用以下脚本。
DECLARE @sql NVARCHAR(MAX)
SELECT @sql=Equery FROM #queryBlock WHERE ID=1
EXEC(@sql)
答案 1 :(得分:1)
每当您必须动态设置列名时,您必须使用动态SQL:
顺便说一句:我很确定,你向我们展示的结构不能满足你的需求......CREATE TABLE #mainTable (id INT, ename VARCHAR(20), eaddress VARCHAR(20))
INSERT INTO #mainTable VALUES
(1, 'A', 'B'),
(2, 'B', 'C'),
(3, 'C', 'D')
CREATE TABLE #mappingTable (ExportField VARCHAR(20), SelectField VARCHAR(20))
INSERT INTO #mappingTable VALUES
(1, 'ID'),
(2, 'EName'),
(3, 'EAddress')
DECLARE @tableName VARCHAR(100)='#mainTable'; -- shouldn't this be configured in #mappingTable
DECLARE @statement VARCHAR(MAX)=
(
SELECT 'SELECT ' + STUFF(
(
SELECT ',' + QUOTENAME(SelectField) + ' AS ' + QUOTENAME(ExportField)
FROM #mappingTable
FOR XML PATH('')
),1,1,''
)
+ ' FROM ' + QUOTENAME(@tableName)
)
PRINT @statement;
--execute this
EXEC(@statement);
GO
DROP TABLE #mappingTable
DROP TABLE #mainTable
创建的声明
SELECT [ID] AS [1],[EName] AS [2],[EAddress] AS [3] FROM [#mainTable]
答案 2 :(得分:0)
我为我的问题找到了非常简单的解决方案,希望你们明白我究竟想要解决我的问题。感谢大家给予您宝贵的时间,并期待更简单的解决方案。我想再次提出有关此解决方案的反馈。对不起@Shnugo你的代码真的不起作用,仍然期待解决方案,我已经测试了http://rextester.com/l/sql_server_online_compiler并得到了评论中提到的相同问题:
DECLARE @sqlQuery VARCHAR(MAX)
SELECT @sqlQuery = Equery FROM #queryBlock WHERE id = 1
SELECT @sqlQuery = REPLACE(@sqlQuery, '['+SelectField+']', '['+ExportField+']')
FROM #mappingTable
EXEC(@sqlQuery)