我试图从数据库中的每个日期列中选择最小日期。我的意思是最小值是我想获得最早的日期。
根据我的调查,似乎最好的方法是使用动态 SQL。这是我目前正在尝试的代码,但我无法从中得到任何东西。
DECLARE @Sql nvarchar(max)
SELECT @Sql = STUFF(
(
SELECT ' UNION ALL SELECT '''+ MIN(C.COLUMN_NAME) +','+''''+ C.TABLE_NAME +''' As TableName FROM '+ C.TABLE_SCHEMA+ '.' +C.TABLE_NAME
FROM Information_schema.Columns C
JOIN Information_schema.Tables T
ON C.TABLE_NAME = T.TABLE_NAME
WHERE C.DATA_TYPE in ('datetime','date','datetime2','timestamp','time')
and C.TABLE_SCHEMA NOT IN ('STG','HIST')
and C.TABLE_SCHEMA IN ('COSTOS')
and T.TABLE_TYPE <> 'VIEW'
GROUP BY C.TABLE_SCHEMA, C.TABLE_NAME
FOR XML PATH('')
), 1, 11, '')
EXEC(@Sql)
SELECT @Sql
我不熟悉动态 SQL,该查询的输出是空结果。
这是基于您的尝试,您需要做的一件事是将
MIN()
放入语句中:
DECLARE @sql nvarchar(max)
DECLARE @err int
SELECT @sql = STUFF(
(
SELECT
'UNION ALL SELECT ' +
QUOTENAME(C.TABLE_NAME, '''') + ' AS [TableName], ' +
QUOTENAME(C.TABLE_SCHEMA, '''') + ' AS [SchemaName], ' +
QUOTENAME(C.COLUMN_NAME, '''') + ' AS [ColumnName], ' +
'MIN(' + QUOTENAME(C.COLUMN_NAME) + ') AS [ColumnValue] ' +
'FROM ' + QUOTENAME(C.TABLE_SCHEMA) + '.' + QUOTENAME(C.TABLE_NAME) + ' '
FROM Information_schema.Columns C
JOIN Information_schema.Tables T ON C.TABLE_NAME = T.TABLE_NAME
WHERE
C.DATA_TYPE IN ('datetime','date','datetime2','timestamp','time')
AND C.TABLE_SCHEMA NOT IN ('STG','HIST')
AND C.TABLE_SCHEMA IN ('COSTOS')
AND T.TABLE_TYPE <> 'VIEW'
FOR XML PATH(''), TYPE
).value('text()[1]', 'nvarchar(max)'), 1, 10, '')
PRINT @sql
EXEC @err = sp_executesql @sql