我遇到的情况是,我有许多表格,这些表格的数据结构相似但在这些行中并不完全相同:
表1
表2
进行一些数据转换后我想要的最终结果是:
表3
还有几个表具有不同但相似的模式,因此我正在编写一个脚本,该脚本将从缺少某些列的各种表中导入表3。
基于this问题,我尝试过这样的查询:
SELECT A
,B
,case
when COL_LENGTH('t2', 'C') IS NULL
then NULL
ELSE C
end as C
FROM t2
但它会抛出“无效的列名C”错误,即使它会选择null。
是否有另一种选择列的方法,如果它存在则为NULL,如果不存在则为NULL?
答案 0 :(得分:1)
此脚本为任何表结构生成动态SQL。
<强>查询:强>
SET NOCOUNT ON
IF OBJECT_ID (N'dbo.Table_1') IS NOT NULL
DROP TABLE dbo.Table_1
IF OBJECT_ID (N'dbo.Table_2') IS NOT NULL
DROP TABLE dbo.Table_2
CREATE TABLE dbo.Table_1 (A INT NOT NULL, B INT NOT NULL, C INT NOT NULL)
CREATE TABLE dbo.Table_2 (A INT NOT NULL, B INT NOT NULL)
INSERT INTO dbo.Table_1 (A, B, C)
VALUES (1, 1, 1), (2, 2, 2)
INSERT INTO dbo.Table_2 (A, B)
VALUES (6, 1), (8, 2)
DECLARE @SQL NVARCHAR(2000)
;WITH cte AS
(
SELECT
column_name = '[' + c.name + ']'
, table_name = '[' + s.name + '].[' + o.name + ']'
FROM sys.columns c WITH (NOLOCK)
JOIN sys.objects o WITH (NOLOCK) ON c.[object_id] = o.[object_id]
JOIN sys.schemas s WITH (NOLOCK) ON o.[schema_id] = s.[schema_id]
WHERE o.name IN ('Table_1', 'Table_2')
AND s.name = 'dbo'
AND o.[type] = 'U'
), cols AS
(
SELECT DISTINCT column_name
FROM cte
), tbl AS
(
SELECT DISTINCT table_name
FROM cte
), rs AS
(
SELECT
tbl.table_name
, column_name = ISNULL(cte.column_name, cols.column_name + ' = NULL')
FROM cols
CROSS JOIN tbl
LEFT JOIN cte ON cols.column_name = cte.column_name AND cte.table_name = tbl.table_name
), rs2 AS (
SELECT uni = ' UNION ALL' + CHAR(13) + 'SELECT ' + STUFF((
SELECT ', ' + rs.column_name
FROM rs
WHERE tbl.table_name = rs.table_name
GROUP BY rs.column_name
ORDER BY rs.column_name
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') +
' FROM ' + table_name
FROM tbl
)
SELECT @SQL = 'SELECT
' + STUFF((
SELECT CHAR(13) + ', ' + cols.column_name
FROM cols
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ' ')
+ '
FROM
(' + STUFF((
SELECT CHAR(10) + uni
FROM rs2
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 11, '') + CHAR(13) +
') t'
PRINT @SQL
EXECUTE sys.sp_executesql @SQL
<强>输出:强>
SELECT
[A]
, [B]
, [C]
FROM
(
SELECT [A], [B], [C] FROM [dbo].[Table_1]
UNION ALL
SELECT [A], [B], [C] = NULL FROM [dbo].[Table_2]
) t
<强>结果:强>
A B C
----------- ----------- -----------
1 1 1
2 2 2
6 1 NULL
8 2 NULL
答案 1 :(得分:0)
你能使用UNION
吗?
select A, B, C FROM Table1
UNION
Select A, B, null FROM Table2