将 SQL 字符串存储在 XML XElement 而不是 String 中以保留换行符
当谈到在代码中存储 SQL 时,大多数人都使用字符串:
Dim strSql As String = "Select Foo, Bar From FooBarTable Where Something = @Something"
问题是,当 SQL 字符串很长时,在代码中读取它们会变得很困难。您通常可以像这样拆分字符串:
Dim strSql As String = "Select Foo, Bar From FooBarTable " & _
"Where Something = @Something"
这会导致许多问题:
- 您无法将其复制到 SSMS 或从 SSMS 复制
- 它 它使用一种低效的方式 (
&
) 来连接字符串(不是这样)这确实很重要,因为您的数据库比字符串类慢几个数量级)
那么为什么不将长 SQL 字符串存储为 System.XML.Linq.XElement 类型呢?
Dim SQL = <SQL>
Select Foo, Bar From FooBarTable
Where Something = @Something
</SQL>
您可以使用SQL.Value
在代码中调用它。
使用此方法,您可以保留换行符和格式,以使其更易于阅读和复制。
我的问题是,基本上,我是否偶然发现了一种在代码中存储多行 SQL 字符串的巧妙方法,或者我在这里完全遗漏了一些东西?它似乎在我的代码中工作,但我不确定它的效率如何。
有什么想法吗?
When it comes to storing SQL in code, most people use strings:
Dim strSql As String = "Select Foo, Bar From FooBarTable Where Something = @Something"
The problem is, when you have very long SQL strings, reading them in code becomes difficult. You can usually split the strings up like this:
Dim strSql As String = "Select Foo, Bar From FooBarTable " & _
"Where Something = @Something"
This causes a number of problems:
- You can't copy it to or from SSMS
- It uses an inefficient way (
&
) of concatenating the string (not that it really matters since your DB is orders of magnitude slower than the string class)
So why not store long SQL strings as a System.XML.Linq.XElement
type?
Dim SQL = <SQL>
Select Foo, Bar From FooBarTable
Where Something = @Something
</SQL>
You can call it in code by using SQL.Value
.
With this method you can preserve line breaks and formatting to make it both easier to read and easier to copy around.
My question is, basically, did I stumble across a clever way to store multi-line SQL strings in code, or am I totally missing something here? It seems to work in my code, but I'm not sure how efficient it is.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是在代码中放置多行字符串常量的好方法。我喜欢它,但我怀疑它的效率要低得多。如果您运行性能分析器并发现出现性能问题,您始终可以将它们替换为字符串常量,但是在开发代码时,在复制和粘贴 SQL 命令时,此方法肯定更容易。
您应该能够简单地使用
SQL.Value
而无需.ToString
调用,因为 Value 属性是一个字符串。I think it's a nice way of placing multi-line string constants in your code. I like it and I doubt it's much less efficient. If you run a performance profiler and discover you've got performance problems, you could always replace them with the string constants, but while you're developing the code, this method is definitely easier when copying and pasting SQL commands.
You should be able to simply use
SQL.Value
without the.ToString
call because the Value property is a string.这就是使用它的方法...效果很好
this is how is use it... it works very well