在 SQL Server 存储过程中通过索引而不是名称访问表的列
有没有办法通过 SQL Server 存储过程中的索引来访问列?
目的是计算大量列。我正在阅读有关游标的内容,但我不知道如何应用它们。
让我解释一下我的问题:
我有一行如下:
field_1 field_2 field_3 field_4 ...field_d Sfield_1 Sfield_2 Sfield_3...Sfield_n
1 2 3 4 d 10 20 30 n
我需要计算类似 (field_1*field1) - (Sfield_1* Sfiled_1) / more...
因此结果存储在表列中d 次。
因此结果是一个 d 列 * d 行
表。
由于列数是可变的,我正在考虑制作动态 SQL,获取字符串中的列名并拆分我需要的列名,但这种方法使问题变得更加困难。我认为通过索引获取列号可以让生活更轻松。
Is there a way to access columns by their index within a stored procedure in SQL Server?
The purpose is to compute lots of columns. I was reading about cursors, but I do not know how to apply them.
Let me explain my problem:
I have a row like:
field_1 field_2 field_3 field_4 ...field_d Sfield_1 Sfield_2 Sfield_3...Sfield_n
1 2 3 4 d 10 20 30 n
I need to compute something like (field_1*field1) - (Sfield_1* Sfiled_1) / more...
So the result is stored in a table column d times.
So the result is a d column * d row
table.
As the number of columns is variable, I was considering making dynamic SQL, getting the names of columns in a string and splitting the ones I need, but this approach makes the problem harder. I thought getting the column number by index could make life easier.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可以,您不能在
SELECT
子句中使用序数(数字)位置。仅在
ORDER BY
子句中才能使用序数位置,因为它基于SELECT
子句中指定的列。No, you can not use the ordinal (numeric) position in the
SELECT
clause.Only in the
ORDER BY
clause can you use the ordinal position, because it's based on the column(s) specified in theSELECT
clause.首先,正如 OMG Ponies 所说,您不能按列的序号位置引用列。这并非偶然。 SQL 规范不是为 DDL 或 DML 中的动态模式构建的。
鉴于此,我不得不想知道为什么你的数据结构如此。当您尝试提取信息时,模式与问题域之间不匹配的迹象就会出现。当查询编写起来非常麻烦时,就表明该模式没有正确地对其设计的领域进行建模。
然而,无论如何,鉴于您告诉我们的情况,替代解决方案将类似于以下内容:(我假设
field_1*field1
应该是field_1 * field_1
或field_1
平方或Power( field_1, 2 )
)现在您的查询如下所示:
First, as OMG Ponies stated, you cannot reference columns by their ordinal position. This is not an accident. The SQL specification is not built for dynamic schema either in DDL or DML.
Given that, I have to wonder why you have your data structured as you do. A sign of a mismatch between schema and the problem domain rears itself when you try to extract information. When queries are incredibly cumbersome to write, it is an indication that the schema does not properly model the domain for which it was designed.
However, be that as it may, given what you have told us, an alternate solution would be something like the following: (I'm assuming that
field_1*field1
was meant to befield_1 * field_1
orfield_1
squared orPower( field_1, 2 )
)Now your query looks like:
这可能不是最优雅或最有效的,但它确实有效。我正在使用它创建一个新表,以便在我需要解析所有列/行的数据之间进行更快的映射。
This might not be the most elegant or efficient but it works. I am using it to create a new table for faster mappings between data that I need to parse through all the columns / rows.