简体   繁体   中英

Generic SQL to get max value given table and column names as varchar

it is very easy to use the following SQL to get value for a specific primary key: ID from a specific table: myTale:

DECLARE @v_maxID bigint;
SELECT @v_maxID = MAX(ID) FROM myTable;

What I need is a generic SQL codes to get the max value for a key from a table, where both key and table are specified as varchar(max) types as parameters:

DECLARE @v_maxID bigint;
-- SELECT @v_maxID = MAX(@p_ID) FROM @p_Table;

I comment out the SELECT since it is not working. I tried to build a SQL string and I can EXEC it, but I cannot get the max value back to my local variable(@v_maxID). Any suggestions?

DECLARE @max bigint, @sql nvarchar(max)
SET @sql = N'SELECT @max = MAX(' + @p_ID + ') FROM ' + @p_Table

EXEC sp_executesql 
    @query = @sql, 
    @params = N'@max bigint OUTPUT', 
    @max = @max OUTPUT 

PRINT @max

Users are choosers, but I consider this an ugly idea (for being overgeneralized). And unoptimizable. Just write the SQL.

Correct me if I'm wrong, but don't you just want:

SELECT MAX(ID) FROM mytable

Just build the query at the app level, thus the query running would be just like the one above. Doing in on sql will certainly open you for sql injection, since you have to use exec(). Also in either case, be careful with user input.

As BC states, you have to use sp_executesql with an OUTPUT parameter.

How to specify output parameters when you use the sp_executesql stored procedure in SQL Server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM