您可以使用这个存储过程:它将年份作为输入参数。它返回在输入年份下具有值的列(及其表名)。
ALTER PROCEDURE [dbo].[sp_GetAllDateColumns] @startDateYear [INT]
AS
BEGIN
SET nocount ON;
-- ---------------
DECLARE @table_name NVARCHAR(100)
DECLARE @col_name VARCHAR(100)
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @count INT
-- ---------------
DECLARE @ResultArray TABLE
(
table_name NVARCHAR(100),
col_name VARCHAR(100)
)
-- ----------------
DECLARE table_cursor CURSOR FOR
SELECT ( SCH.name + '.' + TAB.name )AS tablename,
COL.name AS colname
FROM sys.schemas SCH,
sys.tables TAB,
sys.columns COL,
sys.types TYP
WHERE COL.system_type_id = TYP.system_type_id
AND TAB.object_id = COL.object_id
AND SCH.schema_id = TAB.schema_id
AND TYP.name IN ( 'datetime', 'date' );
OPEN table_cursor
FETCH next FROM table_cursor INTO @table_name, @col_name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlCommand = 'SELECT @cnt = COUNT(*) FROM '
+ @table_name + ' WHERE datepart(year,' +
+ @col_name + ' ) < '
+ CONVERT(NVARCHAR, @startDateYear)
EXECUTE Sp_executesql @sqlCommand, N'@cnt int OUTPUT', @cnt=@count output
IF @count >= 1
BEGIN
INSERT INTO @ResultArray(table_name, col_name)VALUES (@table_name,@col_name)
END
FETCH next FROM table_cursor INTO @table_name, @col_name
END
CLOSE table_cursor
DEALLOCATE table_cursor
--Return result
SELECT * FROM @ResultArray
END
要从 SQL Server 调用此过程,您所要做的就是执行此查询:
EXEC [dbo].[sp_GetAllDateColumns] @startDateYear = 2003