Sql server 不在游标内显示来自动态SQL的选择结果

Sql server 不在游标内显示来自动态SQL的选择结果,sql-server,select,stored-procedures,cursor,dynamic-sql,Sql Server,Select,Stored Procedures,Cursor,Dynamic Sql,我目前正在学习SQL,并试图为自己想出一些练习,尽管这看起来很简单,但我似乎无法让它起作用: 我试图在数据库中的所有过滤表中运行一个游标,以便将该表名传递给一个变量,该变量将在游标内的DynamicSQL中使用。最终结果应该是包含列“empid”的每一列的所有值。 但是,消息返回为“Commands completed successfully”,但尽管使用select语句,我还是看不到任何结果 我试着运行这样的程序: declare @tablename nvarchar(200);

我目前正在学习SQL,并试图为自己想出一些练习,尽管这看起来很简单,但我似乎无法让它起作用:

我试图在数据库中的所有过滤表中运行一个游标,以便将该表名传递给一个变量,该变量将在游标内的DynamicSQL中使用。最终结果应该是包含列“empid”的每一列的所有值。 但是,消息返回为“Commands completed successfully”,但尽管使用select语句,我还是看不到任何结果

我试着运行这样的程序:

    declare @tablename nvarchar(200);
declare @empid int;
declare @sql nvarchar(200) = N'select * from ' + @tablename + N' where empid = ' +@empid;
declare tablecursor cursor for select table_name from information_schema.tables where col_length(table_name, 'empid') is not null;
open tablecursor;
fetch next from tablecursor into @tablename;
while @@fetch_status = 0
begin 
execute sp_executesql @sql, 825
fetch next from tablecursor into @tablename;
end
close tablecursor;
deallocate tablecursor;
我一直在到处寻找答案,但什么也找不到。我尝试将其放入存储过程中,然后从存储过程中执行它,但这也不起作用


非常感谢您的帮助。

DECLARE@SQL应该在while循环的外部,但是在while循环中分配变量

SET @SQL = N'SELECT * FROM ' + @tableName 
应该在while循环中


另一件事是增加@SQL变量的长度。

感谢您的帮助。听了你的建议后,我遇到了更多的错误,但至少对于这些错误,我能够在网上找到答案。我还学到的是,在执行sql字符串时,不能将其置于引号中,因为这将使SSM将@sql视为实际字符串而不是变量。我已经设法让它工作,我的代码现在看起来像这样:

create proc cdr @empid nvarchar(5) as

declare @tablename nvarchar(200);

declare tablecursor cursor for select table_name from information_schema.tables where col_length(table_name, 'empid') is not null;

open tablecursor;

fetch next from tablecursor into @tablename;

declare @sql nvarchar(max)

while @@fetch_status = 0

begin

set @sql = N'select * from ' + @tablename + N' where empid = ' + @empid;

execute sp_executesql @sql

fetch next from tablecursor into @tablename;

end

close tablecursor;

deallocate tablecursor;

不要发布代码的图像;将代码粘贴为文本。请用你的密码回答你的问题。谢谢。嗨@Larnu,我完全知道这会让我的代码对SQL注入开放;然而,我最近了解了动态SQL及其危险性,我还在网上搜索一门关于如何防范SQL注入的综合课程。如果你有任何资料给我,我非常渴望学习和提高自己。这对SQL注入是完全开放的。亲爱的@Larnu,你绝对是真的,它对SQL注入是开放的,但就目前而言,他开始学习,并想了解结果没有出现的原因,所以我解释了这一点。但你是对的,下次我也会提出警告。