视图内带有变量的动态 SQL (SQL Server)
您好,我本质上是尝试在 SQL Server 2008 中的新视图窗口中执行此操作:
声明 @var = (从数据库中选择 db); exec('从'+@var'+.dbo.Names中选择名称);
这个视图实际上在 SQL Server 中运行,但我无法保存它(它给了我一个错误),我可能只创建一个表返回函数,在其中执行所有相同的操作并返回表并创建一个基本上包含所有内容的视图从该表中可以看出,但我不确定这样做可能会导致性能下降。任何建议将不胜感激!谢谢。
解决方案: 我最终让它删除旧视图并在存储过程中重新创建一个新视图(使用动态 sql)。当该值更改时,我将调用 SP,它将更新视图以指向正确的数据库。感谢所有帮助人员,知道什么是不能做的,阻止了我尝试这些方法。
Hello I'm essentially trying to do this inside a new view window in SQL Server 2008:
declare @var = (select db from databases);
exec ('select name from ' + @var ' + .dbo.Names);
This view actually runs in SQL Server but I cannot save it (it gives me an error), I could potentially just create a table returning function, do all of this same stuff in it and return the table and create a view that basically takes everything from that table but I was unsure of performance hits that could occur from doing this. Any suggestions would be greatly appreciated! Thanks.
Solution:
I just ended up having it drop the old view and recreate a new view (using dynamic sql) in a Stored Procedure. When that value is changed I will just call the SP which will update the views to point to the correct databases. Thanks for all the help guys, knowing what can't be done stopped me from trying those methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
视图不能接受参数。表值函数就是解决方案。但您至少必须知道另一端将出现的表和结果集。如果您将要查询的表作为参数传递,您如何知道结果数据集的结构?
View's cannot accept parameters. A table valued function IS the solution. But you have to at least know the table and result set that is going to come out the other end. If your passing the table to be queried as a parameter how do you know the structure of the resulting data set?
您可以使用 CTE 轻松伪造视图中的内部变量。您可以在您的 SQL Server 版本中测试运行它。
产生输出:
也通过
JOIN
也通过
CROSS APPLY
You can easily fake an internal variable in your view using CTE. You can test-run it in your version of SQL Server.
yielding output:
also via
JOIN
also via
CROSS APPLY