简体   繁体   English

通用SQL以表和列名的形式获取最大值作为varchar

[英]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: 使用以下SQL来获取特定主键的值非常容易:来自特定表的ID: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: 我需要的是通用SQL代码,用于从表中获取键的最大值,其中键和表都指定为varchar(max)类型作为参数:

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

I comment out the SELECT since it is not working. 我将SELECT注释掉,因为它不起作用。 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). 我尝试构建一个SQL字符串,可以执行它,但是无法将最大值返回到我的局部变量(@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. 只需编写SQL。

Correct me if I'm wrong, but don't you just want: 如果我错了,请纠正我,但您不只是想要:

SELECT MAX(ID) FROM mytable 从mytable中选择MAX(ID)

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(). 在sql上执行操作肯定会打开sql注入,因为您必须使用exec()。 Also in either case, be careful with user input. 同样在两种情况下,请注意用户输入。

As BC states, you have to use sp_executesql with an OUTPUT parameter. BC所述,您必须将sp_executesql与OUTPUT参数一起使用。

How to specify output parameters when you use the sp_executesql stored procedure in SQL Server 在SQL Server中使用sp_executesql存储过程时如何指定输出参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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