-2

I want to create a T-SQL function, send table name and column name to it, and get the max value of this column.

I wrote a function like this:

CREATE FUNCTION getMaxValue 
     (@TableName nvarchar(30),@FieldName nvarchar(30))
RETURNS nvarchar(max) 
AS  
BEGIN 
    DECLARE @SqlString nvarchar(MAX)
    --declare @Result nvarchar(MAX)

    SET @SqlString = ' select max( ' + @FieldName + ') from ' + @TableName 
    RETURN EXEC(@SqlString)
END

but I can't use EXEC in SET, SELECT or RETURN within this function.

Please help me to solve this problem.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

5

This is a very strange request and will not work in nearly every database I have ever encountered. It also would not make sense in any system I have ever worked with but you can leverage dynamic sql for such a thing. I hope you are patient because this is going to unbelievably slow. But you are asking sql to get you the max value of every single column of every single table. There is no way to do this quickly.

declare @SQL nvarchar(max) = ''

select @SQL = @SQL + 'select ''' + TABLE_NAME + ''' as TableName, ''' + COLUMN_NAME + ''' as ColumnName, cast(Max([' + COLUMN_NAME + ']) as varchar(max)) as MaxValue from [' + TABLE_NAME + '] union all '
from INFORMATION_SCHEMA.COLUMNS

set @SQL = LEFT(@SQL, len(@SQL) - 10)

select @SQL
--uncomment below when you are comfortable with this.
--exec sp_executesql @SQL
Sean Lange
  • 33,028
  • 3
  • 25
  • 40
1

You have to use sp_executesql to run the query

Karim
  • 11
  • 1