如何在查询中将列名称设置为动态 [英] how can i get the column names as dynamic in a query

查看:104
本文介绍了如何在查询中将列名称设置为动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我想动态获取表的列名。我怎样才能在sql中实现这一点。

i want to get the column names of a table dynamically. how can i achieve that in sql.

我将解释你想要它的场景:

i wl explain u the scenario how i want it like:

我有一个只有两行的表。我必须比较第一列的值,如果有不同我们需要将这些值存储在其他表或任何东西(我可以存储的地方),如果它们相等我需要跳过该列并比较第二列
值等等..

i have a table with two rows only. i have to compare values of first column if there are differant we need to store these values in other table or anything (somewhere i can store), if they are equal i need to skip that column and compare the second column values and so on..

如果列数较少,我可以为每个值声明变量并进行比较但是列的数量很大(大约100)。

if there are less columns i can declare variables for each of these values and compare but the no of columns are huge (around 100).

所以我需要动态获取列名。所以我可以把代码放在循环中并重复每一列。

so i need to get the column names dynamically. so that i can put code in loop and repeat for every column.

我试过这样:

我将所有这些列放到一个表中并尝试将一列添加到每个循环的变量(@var)

i put all these columns into one table and tried to fetch one column into a variable(@var) for each loop

并且我写了类似于"select table from table_name"的查询。此查询为我提供了列名称(在table_name中提取为no行)

and i wrote query similar to "select @var from table_name" this query giving me the column name(fetching as no of rows in table_name)

但不是列值。任何人有任何想法吗?

but not column value. any one has any idea?

任何帮助高度赞赏。

谢谢你

推荐答案

首先,此论坛适用于以前代号为Denali的SQL Server 2012,后者是即将推出的SQL Server版本。您的问题似乎与Denali无关。

First of all, this forum is intended for SQL Server 2012, previously codenamed Denali, which is the forthcoming version of SQL Server. It does not seem that your question is related to Denali.


我有一个只有两行的表。我必须比较第一列的值,如果有不同我们需要将这些值存储在其他表或任何东西(我可以存储的地方),如果它们相等我需要跳过该列并比较第二列
值等等..

i have a table with two rows only. i have to compare values of first column if there are differant we need to store these values in other table or anything (somewhere i can store), if they are equal i need to skip that column and compare the second column values and so on..

请问您是如何结束这张桌子的?表应该为唯一实体建模,并且每列应该表示该实体的唯一属性。从这个角度来看,你所要求的,没有意义。也许它最终确实如此,
但是因为你正在弯曲模型,它会很痛苦,因为你不应该做那样的事情。

May I ask how you ended up with this table? A table is supposed to model a unique entity, and each column is supposed to represent a unique attribute of that entity. From that perspective, what you ask for, does not make sense. Maybe it does in the end, but since you are bending the model, it will be painful, because you are not supposed to do things like that.

那么为什么不采取更进一步,也许我们可以为你的整体问题找到更好的解决方案。

So why not take a step further back, and maybe we can find a better solution to your overall problem.


这篇关于如何在查询中将列名称设置为动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆