【发布时间】: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