所以也许这会做你想要的。sys.columns
该查询从命名'%leave%'
为表的地方获取所有列名,dt1
或者dt2
构建一个动态查询,然后执行该查询。它依赖于 sys.columns 和 sys.tables (这可能是坏的)并且具有源表名称dt1
和dt2
硬编码。
在我看来,这不是一个好的解决方案,问题的正确解决方案可能是改变数据模型,使其leave
成为它自己的实体。
我在EXECUTE
最后注释掉了 in 并留下了PRINT
in 这样你就可以在执行它之前看到查询会做什么。
DECLARE @Columns VARCHAR(MAX)
SELECT @Columns = COALESCE(@Columns + ',' + name + '', '' + name + '') FROM (
SELECT DISTINCT
'CAST(ISNULL(dt1.' + name + ',0) AS VARCHAR) + ''/'' + CAST(dt2.' + name + ' AS VARCHAR) AS ' + name + ' ' AS name
FROM sys.columns
WHERE NAME LIKE '%leave%'
AND object_id IN (SELECT object_id FROM sys.tables WHERE name IN ('dt1', 'dt2'))) LeaveColumns
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = N'
SELECT
dt1.empid,
dt1.empname, ' + @Columns + '
FROM dt1
INNER JOIN dt2 ON dt1.empid=dt2.empid'
PRINT @SQL -- Uncomment to see the query which will be run
--EXECUTE(@SQL)
对我来说,这给出了以下输出(表结构略有改变,其中包含更多leave
列):
SELECT
dt1.empid,
dt1.empname,
CAST(ISNULL(dt1.casualleave,0) AS VARCHAR) + '/' + CAST(dt2.casualleave AS VARCHAR) AS casualleave ,
CAST(ISNULL(dt1.sickleave,0) AS VARCHAR) + '/' + CAST(dt2.sickleave AS VARCHAR) AS sickleave ,
CAST(ISNULL(dt1.someotherleave,0) AS VARCHAR) + '/' + CAST(dt2.someotherleave AS VARCHAR) AS someotherleave ,
CAST(ISNULL(dt1.yetanotherleave,0) AS VARCHAR) + '/' + CAST(dt2.yetanotherleave AS VARCHAR) AS yetanotherleave
FROM dt1
INNER JOIN dt2 ON dt1.empid=dt2.empid