简体   繁体   English

如何在SQL 2005中将变量设置为表名称的SQL查询结果的变量

[英]How to set a variable to the result of a sql query with a variable as a table name in SQL 2005

I'm currently having trouble writing a stored procedure and setting the value of a variable of type int to the results of a select statement with a variable as the tablename. 我目前在编写存储过程以及将int类型的变量的值设置为带有变量作为表名的select语句的结果时遇到麻烦。 I've looked at old threads and tried multiple methods, but no luck. 我查看了旧线程并尝试了多种方法,但是没有运气。 If I'm not getting an error regarding the tablename, I end up getting an error with a variable conversion issue. 如果没有关于表名的错误,我最终会因为变量转换问题而出错。 I've been working on this for too long and any help would be appreciated. 我已经为此工作了很长时间,我们将不胜感激。 Below is a portion of my code. 以下是我的代码的一部分。 Thanks 谢谢

DECLARE @BATCHNUMBER VARCHAR  --value set in earlier code
DECLARE @ETABLE VARCHAR(50); --the table name
DECLARE @FIRSTDOCID INT;      
SET @ETABLE = 'tablename_' + @BATCHNUMBER; --CREATE FIRST TABLE NAME

SELECT @FIRSTDOCID = MIN(D0CID) FROM @ETABLE

The error I get is: Must declare the table variable "@ETABLE" 我得到的错误是:必须声明表变量“ @ETABLE”

You are trying to select from a VARCHAR , not a table. 您正在尝试从VARCHAR而不是表中进行选择。 The only way to make this work is by using Dynamic SQL. 进行此工作的唯一方法是使用动态SQL。

DECLARE @SQL NVARCHAR(250);
SET @SQL = 'SELECT @OUTPUT = MIN(D0CID) FROM ' + QuoteName(@ETABLE);
EXEC sp_executeSql @SQL, N'@output INT OUTPUT', @FIRSTDOCID OUTPUT;

SELECT @FIRSTDOCID;

However, I would not suggest using Dynamic SQL as this often leads to SQL injection. 但是,我不建议使用动态SQL,因为这通常会导致SQL注入。

You'll probably have to do something like use exec if you're dynamically building the query: 如果要动态构建查询,则可能必须执行use exec之类的操作:

SET @QUERY = "SELECT" + ...etc.
exec(@QUERY)

Since ETABLE is a varchar, and not, as expected, a 'table variable'. 由于ETABLE是varchar,而不是预期的“表变量”。

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

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