Search code examples
sqlsql-servercomparemaxlength

SQL Union select get max length from result


I have query against a SQL Server database:

Select [Surname] 
from [dbo].[customer] 

union 

Select 'Surname';

As result I have:

SQL result

and I want get from result max(len( {result} ));. If I use:

Select max(len([Surname])) 
from [dbo].[customer];

This is working correctly (in result I have 11), but I need add to compare column name.

Query:

Select max(len(Select [Surname] 
               from [dbo].[customer] 
               union 
               Select 'Surname'))

Return error:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'select'.

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ')'.


Solution

  • Try changing it to

    Select max(len([Nazwisko]))
    FROM (Select [Nazwisko] from [dbo].[wlasciciel] union Select 'Surname') t