【问题标题】:Not displaying select results from dynamic SQL within Cursor不显示来自游标内动态 SQL 的选择结果
【发布时间】:2018-11-03 13:47:47
【问题描述】:

我目前正在学习 SQL 并尝试为自己考虑练习,尽管这看起来很简单,但我似乎无法完成这项工作:

我正在尝试通过我的数据库中的所有过滤表运行游标,以便我可以将该表名传递给一个变量,该变量将在游标内的 DynamicSQL 中使用。最终结果应该是每列中包含“empid”列的所有值。 但是,消息返回为“命令已成功完成”,但尽管我使用了 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;

我一直在到处寻找使这项工作有效的答案,但找不到任何东西。我试过放入一个存储过程,然后从那里执行它,但也没有用。

我们将不胜感激。

【问题讨论】:

  • 不要发布你的代码图片;将代码粘贴为文本。请edit您的代码问题。谢谢。
  • 嗨@Larnu,我完全知道这会使我的代码对SQL注入开放;但是,我最近了解了动态 SQL 及其危险,我仍在网上搜索有关如何防御 SQL 注入的综合课程。如果你有任何资料给我,我非常渴望学习和提高自己。

标签: sql-server select stored-procedures cursor dynamic-sql


【解决方案1】:

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

SET @SQL = N'SELECT * FROM ' + @tableName 

应该在while循环中。

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

【讨论】:

  • 这对 SQL 注入完全开放
  • 亲爱的@Larnu,您绝对正确,它对 SQL 注入开放,但目前他开始学习并想了解结果没有出现的原因,所以我解释了那。但你是真的,下次我也会发出警告。
【解决方案2】:

感谢您的帮助。在我听取了您的建议后,我遇到了更多错误,但至少对于这些我能够在网上找到答案。我还了解到,执行时不能将 sql 字符串放在引号中,因为这会使 SSMS 将 @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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 2021-11-25
    • 2015-02-25
    • 1970-01-01
    相关资源
    最近更新 更多