sql – 如何在多个表中获取Date的Max Date Value列

例如,我在数据库中有2个表.
例如:
表T:

declare @t table (name varchar(20),DOB date)
Insert into @t (name,DOB) values ('Mohan','2001-07-19')
Insert into @t (name,DOB) values ('Minu','1998-06-19')

表:TT

declare @tt table (name varchar(20),DOB date)
Insert into @tt (name,DOB) values ('Raju','2010-07-19')
Insert into @tt (name,DOB) values ('Rani','2001-06-19')

现在我有一个Query来获取基于Date类型过滤器的多个表的表名和列名.

SELECT   C.TABLE_SCHEMA, c.TABLE_NAME,c.COLUMN_NAME
FROM     INFORMATION_SCHEMA.COLUMNS c 
         JOIN sys.objects o ON o.name = c.TABLE_NAME   
WHERE    o.type = 'U' AND C.DATA_TYPE = 'Datetime'

输出:

T_Schema    T_name T_column
  dbo         T      DOB   
  dbo         TT     DOB

但是如何获得两个表的最大日期,如下面的输出:

  T_Schema  T_name T_column  Max_dt
  dbo         T      DOB     2001-07-19
  dbo         TT     DOB     2010-07-19

建议我实现这一目标的最佳方法.

最佳答案
SQL为您构建SQL

DECLARE @SQL as nvarchar(max) ='';
select @SQL = @SQL + 'SELECT ' + Column_Name + ' adate, ''' + Column_Name + ''' colname, ''' + Table_name + ''' tabname  FROM ' +  Table_name + ' UNION ' FROM   INFORMATION_SCHEMA.COLUMNS where data_type like '%date%'
select @SQL = 'SELECT TOP 100 * FROM (' + LEFT(@SQL, LEN(@SQL) -6) + ') IQ  WHERE IQ.adate IS NOT null ORDER BY IQ.adate DESC';

 --cut n paste the sql below, see what it does for you
select @SQL

mark II – 为您执行sql,并在其中排序带有空格的名称

DECLARE @SQL as nvarchar(max) ='';
select @SQL = @SQL + 'SELECT [' + Column_Name + '] adate, ''' + Column_Name + ''' colname, ''' + Table_name + ''' tabname  FROM [' +  Table_name + '] UNION ' FROM   INFORMATION_SCHEMA.COLUMNS where data_type like '%date%'
select @SQL = 'SELECT TOP 100 * FROM (' + LEFT(@SQL, LEN(@SQL) -6) + ') IQ  WHERE IQ.adate IS NOT null ORDER BY IQ.adate DESC';

select @SQL;
EXEC sp_executesql @sql;

转载注明原文:sql – 如何在多个表中获取Date的Max Date Value列 - 代码日志