试试这个——
DDL:
SET NOCOUNT ON;
IF OBJECT_ID (N'dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
CREATE TABLE dbo.Table1
(
EmployeeId INT
, Name VARCHAR(30)
, [Address] VARCHAR(150)
, Mode INT
, Img IMAGE
, UpdateDate DATETIME
, IpAddress VARCHAR(20)
)
IF OBJECT_ID (N'dbo.Table2') IS NOT NULL
DROP TABLE dbo.Table2
CREATE TABLE dbo.Table2
(
EmployeeId INT
, Gender VARCHAR(6)
, BloodGroup VARCHAR(20)
, Mode INT
)
INSERT INTO dbo.Table1 (EmployeeId, Name, [Address], Mode, UpdateDate, IpAddress)
VALUES ('001', 'abc', 'No.9,vv street', 1,'06/04/2013 12:00:00','192.168.0.1')
INSERT INTO dbo.Table2 (EmployeeId, Gender, BloodGroup, Mode)
VALUES ('001', 'Male', 'O+ve', 1)
询问:
DECLARE @SQL NVARCHAR(MAX)
;WITH cte AS
(
SELECT
column_name = '[' + c.name + ']'
, table_name = '[' + s.name + '].[' + o.name + ']'
, [type_name] = t.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]
JOIN sys.types t WITH (NOLOCK) ON c.user_type_id = t.user_type_id
WHERE o.name IN ('Table1', 'Table2')
AND s.name = 'dbo'
AND o.[type] = 'U'
AND c.name NOT IN ('Mode', 'UpdateDate', 'IpAddress')
), unicol AS (
SELECT TOP 1 column_name
FROM cte
GROUP BY cte.column_name
HAVING COUNT(cte.column_name) > 1
), cols AS
(
SELECT DISTINCT column_name, [type_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) + ', ' + ISNULL(unicol.column_name, cols.column_name + ' = MAX('
+ CASE
WHEN [type_name] = 'image' THEN 'CONVERT(VARBINARY(MAX), ' + cols.column_name + ')'
WHEN [type_name] = 'bit' THEN 'CAST(' + cols.column_name + ' AS CHAR(1))'
ELSE cols.column_name
END + ')')
FROM cols
LEFT JOIN unicol ON cols.column_name = unicol.column_name
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
GROUP BY ' + (SELECT column_name FROM unicol)
PRINT @SQL
EXECUTE sys.sp_executesql @SQL
输出:
Address BloodGroup EmployeeId Gender Img Name
------------------ ------------ ----------- ------ -------- -------
No.9,vv street O+ve 1 Male NULL abc