我们需要将两个表合并到一个单独的视图中。通常我会单独选择列以避免此问题,但在这种情况下,这两个表是组合的800列。
唯一相同的列是标识符列。不幸的是,这些不能被更改,因为它们被第三方工具用于同步表
Table A
GUID
Name
Address
...
Table B
GUID
Cell
Fax
Home2
...
是很好的例子,假设每个表有400个奇数列。
显然是传统的
SELECT a.*, b.* from table_a a, table_b a where a.guid = b.guid
悲惨地失败。有没有简单的方法来创建视图而不必列出799个单独的列名?我想也许是创造视图的一次性功能,但到目前为止,我正在撞墙。
答案 0 :(得分:0)
您可以使用动态SQL作为解决方案。
CREATE TABLE test1 (id INT, col1 NVARCHAR(50), col2 NVARCHAR(50))
GO
CREATE TABLE test2(id INT, col1 NVARCHAR(50), col2 NVARCHAR(50))
GO
DECLARE @sql NVARCHAR(max) = ''
; WITH cte AS (
SELECT
CASE WHEN TABLE_NAME = 'test1' THEN TABLE_NAME + '.' + COLUMN_NAME + ' AS ' + + COLUMN_NAME + 't1' ELSE TABLE_NAME + '.' + COLUMN_NAME + ' AS ' + + COLUMN_NAME + 't2' END AS a, 1 AS ID
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN ('test1', 'test2')
)
SELECT @sql =
'CREATE VIEW myview as
select ' + (
SELECT
STUFF(
(
SELECT ', '+ [A]
FROM cte
WHERE ID = results.ID
FOR XML PATH(''), TYPE
).value('(./text())[1]','VARCHAR(MAX)')
,1,2,''
) AS NameValues
FROM cte results
GROUP BY ID
) + ' from test1 join test2 on test1.id = test2.id'
PRINT @sql
--EXEC (@sql)
结果是
CREATE VIEW myview
AS
SELECT test1.id AS idt1 ,
test1.col1 AS col1t1 ,
test1.col2 AS col2t1 ,
test2.id AS idt2 ,
test2.col1 AS col1t2 ,
test2.col2 AS col2t2
FROM test1
JOIN test2 ON test1.id = test2.id