I am to create a function to read a table containing some 65 tables and find all columns containing dates, which are stored mostly as int, sometimes as char or datetime. Column names are unknown but I assume ending in ‘%Date’.
I need to find the MAX ie latest date for each client based on his/her SSN. However, the SSN is also called different names, e.g. SSN, SSN_Nr, SSN_No, etc. My code below is hopelessly wrong:
CREATE FUNCTION dbo.LastActivityDate (@SSN varchar(10))
RETURNS datetime
AS
BEGIN
DECLARE @Result datetime
DECLARE @SSN varchar(10)
DECLARE @tableSSN varchar(10)
DECLARE @table varchar(100)
DECLARE @column_name nvarchar(100)
DECLARE @tableDate datetime
DECLARE @LastActivityDate datetime
SET @column_name='%DATE' --only ends in date, so as not to pick up 'update_office',etc
if @SSN IS NULL OR @SSN = '' OR @SSN = ' '
begin
BREAK
end
else
begin
WHILE select Table_Name,Field1 from dbo.MERGE_TABLES where [Enabled]='Y' AND Field1=@SSN
BEGIN
SET @table = Table_Name
SET @tableSSN = Field1
declare @column_name nvarchar(100)
set @table = 'e_client'
set @column_name='%DATE' --only ends in date, so as not to pick up 'update_office',etc
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=@table AND column_name LIKE @column_name ORDER BY ordinal_position
IF ISDATE(SELECT .... FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=@table AND column_name LIKE @column_name)=1
begin
CONVERT(datetime,(SELECT .... FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=@table AND column_name LIKE @column_name))
end
.
.
.
IF (Select MAX([@tableDate]) from @table where @tableSSN=@SSN) > @LastActivityDate --column like FinishDate, proposedFinishDate or startdate if finish is empty
begin
@LastActivityDate=@tableDate
end
END
end--@SSN
SET @Result=@LastActivityDate
RETURN @Result
END
GO
Some problems cry out for automation. I don’t think this is one of them.
I wouldn’t trust a script to get it right in this database. I think you should look at each table, and determine by eye which columns contain dates and which columns contain SSANs. Even if it takes you 5 minutes a table, that’s still less than a day’s work.
If you have to do it a second time, then you can automate it, based on your new-found knowledge of the tables and columns.
If you worked here, you could use a text tool to find all the SSAN columns, because they’d all be based on a
CREATE DOMAINstatement, like (PostgreSQL)