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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Max function to select from a variable

Status
Not open for further replies.

albitzt

Technical User
Sep 8, 2010
13
US
The code is already written and at this point I'm not reflecting on it and I was wondering what I was missing, or if you simply cannot do this. In the below example, what I was looking to do is this:

SELECT @PKVAL=max(@PK_COL_NAME) from pcattype

Thanks in advance.



-------------------------------------------------------------
DECLARE @NEXTKEY_COL_NAME char(50)
DECLARE @PK_COL_NAME char(50)
DECLARE @NKVAL varchar(50)
DECLARE @PKVAL varchar(50)


SET @NEXTKEY_COL_NAME = 'pcattype_proj_catg_type_id'
SET @PK_COL_NAME = 'proj_catg_type_id'


SELECT @NKVAL=key_seq_num from nextkey where key_name = @NEXTKEY_COL_NAME
SELECT @PKVAL=max(proj_catg_type_id) from pcattype
PRINT @NEXTKEY_COL_NAME
IF @NKVAL > @PKVAL
PRINT 'OKAY'
ELSE
PRINT 'FAIL'
PRINT 'NKVAL: ' + @NKVAL
PRINT 'PKVAL: ' + @PKVAL
PRINT ' '
go
 
You need to use dynamic SQL if you want to query a dynamic column.

So, your code will be
Code:
declare @SQL nvarchar(max)

set @SQL = N'select @PkVal = MAX(' + quotename(@Pk_Col_Name) + ') from dbo.pcAtype'

execute sp_ExecuteSQL @SQL, N'@PkVal int OUTPUT', @PkVal OUTPUT

PluralSight Learning Library
 
Makes sesnse..Thanks for the response.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top