将文本转换为数据库对象和字段标识符
给定一个列出所有表和列的 select 语句,如何将表和列名称转换为可在单独的 select 语句中使用的标识符?
换句话说,如果我有字符串 @Table = 'Person' 和 @Column = 'Name',我想要这样的东西:
select
DATALENGTH(MAX(t.@Column)) as Longest,
DATALENGTH(MIN(t.@Column)) as Shortest
from @Table as t;
当然,这并不能实现我想要的。我想知道存储在列中的最长和最短字符串的长度。如果我想要单个列的此信息,则无需使用这些字符串化变量。但我想对数据库中的每个 (varchar) 列执行此操作。生命太短暂,无法创建每条 SQL 语句来完成此任务。这就是为什么我需要一个参数机制来指定表和列。我该如何解决这个问题以实现目标?
当然,我的想法可能全错了。也许我应该按索引寻址每一列,并仅在需要输出时才转换为列名。想法?
Given a select statement that lists all my tables and columns, how do I convert the table and column names into identifiers that can be used in a seperate select statement?
In other words, if I have the string @Table = 'Person' and @Column = 'Name', I want something like this:
select
DATALENGTH(MAX(t.@Column)) as Longest,
DATALENGTH(MIN(t.@Column)) as Shortest
from @Table as t;
Of course that does not accomplish what I want. I want to know the length of the longest and shortest string stored in a column. If I wanted this information for a single column, there would be no need to use these stringified-variables. But I want to do this for every (varchar) column across my database. Life is too short to create every SQL statement to accomplish this. This is why I want a parametric mechanism for specifying the table and column. How do I fix this to achieve the goal?
Of course I could be going about this all wrong. Perhaps I should address each column by index, and convert to a column name only when output is needed. Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不熟悉 tsql,特别是动态 sql,那么这是一本很好的读物,其中介绍了您应该考虑的事项。大多数人在发现动态 SQL 时会想到各种用途以及可以用它做的事情。但就像我说的……要小心。
http://www.sommarskog.se/dynamic_sql.html
If you are new to tsql and specifically dynamic sql this is a good read on things you should consider. Most people, when they discover dynamic sql think of all kinds of uses and things they can do with it. But like I said... take caution.
http://www.sommarskog.se/dynamic_sql.html