Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Variables in Aggregate Functions??

Status
Not open for further replies.

charliescott

IS-IT--Management
Joined
Aug 10, 2005
Messages
7
Location
US
I'm fairly certain there is a very quick and simple solution to the following issue that I'm having...


USE Northwind

DECLARE @COLUMN_NAME VARCHAR(50)
SELECT @COLUMN_NAME='LastName'

--Following result = 8 (Represents the actual length of string 'LastName'

SELECT MAX(LEN(@COLUMN_NAME)) FROM Employees

--Expected / Correct result = 9 (Represents the max length for actual values stored in LastName field of Employees table)

SELECT MAX(LEN(LastName)) FROM Employees
 
One method...

Code:
DECLARE @COLUMN_NAME VARCHAR(50)
SELECT @COLUMN_NAME='LastName'

[!]DECLARE @SQL VarChar(8000)
Set @SQL = '[/!]
SELECT MAX(LEN([!]' + @COLUMN_NAME + '[/!])) FROM Employees[!]'[/!]

[!]Exec (@SQL)[/!]

This method is called dynamic SQL and certainly has its drawbacks regarding security and performance. Do a little research before using this method.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top