如何重构 T-SQL 存储过程,将其参数封装到类中
在我的 SQL Server 2008
上,我有一个包含大量参数的存储过程
。
其中第一部分在每次调用中都会使用,第二部分的参数很少使用。我无法将逻辑移动到两个不同的存储过程。
有没有办法将所有这些参数封装到 class
或 struct
并将其作为存储过程参数传递?
我可以使用SQL CLR
吗?还有其他方法吗?
On my SQL Server 2008
I have a stored procedure
with a large number of parameters.
The first part of them is used in every call and parameters from the second part are used rarely. And I can't move the logic to two different stored procedures.
Is there a way to encapsulate all this parameters to a class
or struct
and pass it as a stored procedure parameter?
Can I use SQL CLR
. Are there other ways?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过表值参数?
实际上,我不会将 CLR 函数用于任何可以在 t-SQL 中有效且轻松完成的事情。例如,上次我使用 CLR 函数是根据一些复杂的正则表达式更新列,我发现这在 t-SQL 中很难做到。
Have you tried Table Valued Parameters?
Actually, I wont use CLR function for anything which can be done effectively and easily in t-SQL. For example, last time I used CLR function is for updating a column based on some complex regex which I found pretty hard to do in t-SQL.
听起来您担心的是需要为每个参数指定值。将默认值分配给不经常使用的参数(这样您就不需要在每次调用过程时传递每个参数)是否有效?
CLR 类型可能是一个选项(XML 也可以),但我不确定沿着这条路走下去是否是一个好主意。
It sounds like your concern is with the need to specify values for each parameter. Would it work for you to just assign default values to the parameters that aren't used as often (so you don't need to pass every parameter each time the proc is called)?
A CLR type could be an option (as could XML) but I'm not sure it would be a good idea to go down that route.
如果参数量导致应用程序出现问题,您可以尝试以下两种方法之一:
1) 传入包含所有参数数据的 XML 数据类型的单个参数。然后你就可以解析出你需要什么。请参阅 XML (Transact-SQL)。
2)创建表参数,请参阅表值参数(数据库引擎),其中表格为:
使用这两种方法中的任何一种,您很可能需要将它们扩展到局部变量中才能再次使用它们。
If the volume of parameters is causing you problems in your application you could try one of the following two methods:
1) pass in a single parameter of XML data type that contains all of the parameters data. you could then parse out what you need. See xml (Transact-SQL).
2) create a table parameter, see Table-Valued Parameters (Database Engine), where the table is:
With either of these methods, you'd more than likely need to expand them out into local variables to use them again.