简体   繁体   English

如何根据表中的顺序选择列

[英]how to select column based on its on order in Table

I want to select Column from Table based on Its Order like 我想根据其顺序从表中选择列

create Table Products
(
  ProductId Int,
  ProductName varchar(50)
)

lets Say I don't Know the name of the second column. 可以说我不知道​​第二列的名称。

How I can get it like : 我如何得到它像:

Select Col1,Col2 From Product

For SQL Server: 对于SQL Server:

You can't do this in the SELECT clause. 您不能在SELECT子句中执行此操作。 You can't select based on the order number of the column. 您无法基于列的订单号进行选择。 You have to list the columns' names you need to select explicitly, otherwise, use SELECT * to list all. 您必须列出需要显式选择的列名,否则,请使用SELECT *列出所有列。 Me be if you are using a data reader object or any other ado.net methods to get the data from database you can do something like this, but this will be based on the column names list listed in your SQL statement. 如果您正在使用数据读取器对象或任何其他ado.net方法从数据库中获取数据,则可以执行以下操作,但这将基于SQL语句中列出的列名列表。

However, you can do something like this dynamically, by reading columns' metadata ordinal_position from information_schema.columns as explained in the following answer: 但是,您可以通过从information_schema.columns读取列的元数据ordinal_position来动态地执行这样的操作,如以下答案所示:

But, you can do this in the ORDER BY clause. 但是,您可以在ORDER BY子句中执行此操作。 You can ORDER BY column number: 您可以按列号ORDER BY

SELECT *
FROM TableName
ORDER BY 2; -- for col2

But this is not recommended to use in ORDER BY or in the SELECT (if any). 但这不建议在ORDER BYSELECT (如果有)中使用。 Furthermore, columns order is not significant in the relational model. 此外,列顺序在关系模型中并不重要。

Update: If you want to select at least 3 columns from any table parameter passed to your stored procedure. 更新:如果要从传递给存储过程的任何表参数中至少选择3列。 Try this as follows: 尝试如下操作:

Your stored procedure supposed to receive a parameter @tableNameParam . 您的存储过程应该接收参数@tableNameParam The folowing code should return the first three columns from the @tablenameParam passed to the stored procedure: 以下代码应返回@tablenameParam传递到存储过程的前三列:

DECLARE @col1 AS VARCHAR(100);
DECLARE @col2 AS VARCHAR(100);
DECLARE @col3 AS VARCHAR(100);
DECLARE @tableNameParam AS VARCHAR(50) = 'Tablename';

DECLARE @sql AS VARCHAR(MAX) ;

SELECT @col1 = column_name FROM information_schema.columns 
                           WHERE table_name = @tableNameParam
                             AND ordinal_position = 1;

SELECT @col2 = column_name FROM information_schema.columns 
                           WHERE table_name = @tableNameParam;
                             AND ordinal_position = 2;

SELECT @col3 = column_name FROM information_schema.columns 
                           WHERE table_name = @tableNameParam;
                             AND ordinal_position = 3;

SET @sql = 'SELECT ' + col1 + ',' + col2 ' + 'col3 ' + FROM ' + @tablename; 

你总是可以做

select * from Product

I'd like to share the following code as a solution to CRUD processing on Ordinal Position within a table. 我想分享以下代码,作为对表内Ordinal Position进行CRUD处理的解决方案。 I had this problem today and it took me quite a long time to research and find a working solution. 我今天遇到了这个问题,花了我很长时间研究和找到可行的解决方案。 Many of the posted answers indicated that it was not possible to interact with the tables columns on an Ordinal bases but as indicated in the post above using the information_schema table will allow using the column position. 许多已发布的答案表明无法与Ordinal基础上的表列进行交互,但是如上一博文所述,使用information_schema表可以允许使用列位置。

My situation was interacting with a table populated through the use of a pivot view so the columns are always changing based on the data, which is fine in a view result but when the dataset is stored into a table the columns are dynamic. 我的情况是与使用枢轴视图填充的表进行交互,因此列始终根据数据而变化,这在视图结果中很好,但是当数据集存储到表中时,列是动态的。 The column names are a Year-Month combination such as 201801, 201802 with an Item Number as a primary key. 列名称是“年-月”组合,例如201801、201802,其中项目编号为主​​键。 This pivot table is to indicate manufacturing quantities by Year-Month on a rolling 12 month period so each month the column names with change/shift which changes their ordinal position when the table is rebuilt each month. 该数据透视表将在12个月的滚动月份中按年/月指示制造数量,因此每个月的列名称都会发生更改/班次,这会在每月重建表时更改其顺序位置。

The Pivot view is used to build the Staging table, The Staging table is used to build the Target table so the ordinal position of the staging and target tables are lined up with the same ordinal position. “数据透视”视图用于构建暂存表,“暂存”表用于构建目标表,因此,暂存表和目标表的顺序位置以相同的顺序位置对齐。

            Declare @colname    Varchar(55) -- Column Name
            Declare @ordpos     INT         -- Ordinal Position
            Declare @Item       Varchar(99) -- PK
            Declare @i          INT         -- Counter
            Declare @cnt        INT         -- Count
            Declare @ids        table(idx int identity(1,1), Item Varchar(25))
        -- Item List
                Insert INTO @ids Select Item From DBName.Schema.TableName   
                    select @i = min(idx) - 1, @cnt = max(idx) from @ids
        -- Row Loop
                While @i < @cnt
                Begin
                    Select @i = @i + 1
                    Set @ordpos=3
                    Set @Item = (select Item from @ids where idx = @i)
        --   Column Loop
                    While @ordpos < 27
                        Begin
                            Select @colname =column_name From INFORMATION_SCHEMA.Columns Where table_name='TargetTable' and ordinal_position=@ordpos
                            Exec ('Update TargetTable set ['+@colname+']= (Select ['+@colname+'] From StagingTable Where Item='''+@Item+''')         where Item='''+@Item+'''')
                            Set @ordpos=@ordpos + 1
                        End -- End Column Loop
                End -- End Row Loop

The code here will loop through the Item matrix by rows and by columns and uses Dynamic SQL to build the action, in this case the action is an update but it could just as easily be a select. 此处的代码将按行和按列循环遍历Item矩阵,并使用Dynamic SQL来构建操作,在这种情况下,该操作是更新,但也可以很容易地将其作为选择。 Each column is processed through the While Loop and then loops through the next row. 每列都通过While循环进行处理,然后遍历下一行。 This allows updates to a specific cell in the matrix by (Item X YearMonth) without actually knowing what the column name at a given position. 这允许通过(Item X YearMonth)更新矩阵中的特定单元格,而无需实际知道给定位置的列名。

The one concern is that depending on the size of the data in this matrix it can be SLOW. 一个问题是,取决于此矩阵中数据的大小,它可能很慢。 I just wanted to show this as a way to use unknown column names in an ordinal position. 我只是想将其显示为在顺序位置使用未知列名称的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM