DECLARE @mxDate DATE
SET @mxDate = (SELECT TOP 1 date FROM Nitgen.dbo.historyDate)
SET @sql = 'SELECT';
SET @sql += ' O.Emp+'' ''+O.date+O.time ';
SET @sql += 'FROM ';
SET @sql += '( ';
SET @sql += ' SELECT ';
SET @sql += ' LEN(''TUF''+B.EmployeeCode) AS NUM, ';
SET @sql += ' CASE ';
SET @sql += ' WHEN LEN(''TUF''+B.EmployeeCode) = 8 THEN ''TUF''+B.EmployeeCode+'' '' ';
SET @sql += ' WHEN LEN(''TUF''+B.EmployeeCode) = 9 THEN ''TUF''+B.EmployeeCode+'' '' ';
SET @sql += ' WHEN LEN(''TUF''+B.EmployeeCode) = 10 THEN ''TUF''+B.EmployeeCode ';
SET @sql += ' END AS Emp, ';
SET @sql += ' CONVERT(varchar, A.TransactionTime, 112) AS date, ';
SET @sql += ' REPLACE(CONVERT(varchar, A.TransactionTime, 108),'':'', '''') AS time, ';
SET @sql += ' A.TransactionTime ';
SET @sql += ' FROM Nitgen.dbo.AUTHLOG A ';
SET @sql += ' INNER JOIN Nitgen.dbo.USER_STG B ON A.UserID = B.UserId ';
SET @sql += ' WHERE LEN(''TUF''+B.EmployeeCode) <= 10 AND LEN(''TUF''+B.EmployeeCode) >= 8 AND A.isFlag IS NULL AND replace(convert(varchar(255),A.TransactionTime,111),''/'',''-'') = '''+@mxDate+''' ';
SET @sql += ') O ';