SQL返回表的前两列

时间:2011-02-07 17:26:41

标签: sql sql-server-2008

是否有任何SQL术语只返回表格的前两个columns 没有知道字段名称

这样的东西
SELECT Column(1), Column(2) FROM Table_Name

或者我是否需要走很长的路才能找到列名?我该怎么做?

8 个答案:

答案 0 :(得分:7)

您必须先获取列名称。大多数平台都支持这一点:

select column_name,ordinal_position
  from information_schema.columns
 where table_schema = ...
   and table_name = ...
   and ordinal_position <= 2

答案 1 :(得分:3)

declare @select varchar(max)
set @select = 'select '

select @select=@select+COLUMN_NAME+','
from information_schema.columns
where table_name = 'TABLE' and ordinal_position <= 2

set @select=LEFT(@select,LEN(@select)-1)+' from TABLE'
exec(@select)

答案 2 :(得分:1)

我一段时间写了一个存储过程来做这个确切的工作。即使在关系理论中没有技术列顺序,SSMS也不是完全关系的。系统存储插入列的顺序并为其分配ID。使用典型的SELECT *语句遵循此顺序,这就是为什么SELECT语句每次都返回相同的顺序。在实践中,SELECT *与任何东西都不是一个好主意,因为它不会在列或行方面锁定结果顺序。这就是说,我认为人们如此坚持“你不应该这样做”他们不会编写实际可以做到的脚本。事实是有可预测的系统行为,所以如果任务不是非常重要,为什么不使用它。

这个SPROC当然有注意事项并且是用T-SQL编写的,但是如果你想要返回所有具有SELECT *相同行为的值,那么这对你来说应该很容易。输入你的表名,列数,然后点击F5。它按照从左到右的顺序返回它们,就像你期望的那样。我将它限制为只有5列,但如果您需要,可以编辑逻辑。采用临时表和永久表。

EXEC OnlySomeColumns'MyTable',3

/*------------------------------------------------------------------------------------------------------------------

    Document Title: The Unknown SELECT SPROC.sql

    Created By: CR
    Date: 4.28.2013

    Purpose: Returns all results from temp or permanent table when not knowing the column names

    SPROC Input Example: EXEC OnlySomeColumns 'MyTable', 3

--------------------------------------------------------------------------------------------------------------------*/

    IF OBJECT_ID ('OnlySomeColumns', 'P') IS NOT NULL
    DROP PROCEDURE OnlySomeColumns;

    GO

        CREATE PROCEDURE OnlySomeColumns 
                @TableName      VARCHAR (1000),
                @TotalColumns   INT

    AS

        DECLARE @Column1        VARCHAR (1000), 
                @Column2        VARCHAR (1000), 
                @Column3        VARCHAR (1000), 
                @Column4        VARCHAR (1000), 
                @Column5        VARCHAR (1000), 
                @SQL            VARCHAR (1000),
                @TempTable      VARCHAR (1000),
                @PermanentTable VARCHAR (1000),
                @ColumnNamesAll VARCHAR (1000)

        --First determine if this is a temp table or permanent table
        IF @TableName     LIKE '%#%' BEGIN SET @TempTable      = @TableName END --If a temporary table
        IF @TableName NOT LIKE '%#%' BEGIN SET @PermanentTable = @TableName END --If a permanent column name

    SET NOCOUNT ON

        --Start with a few simple error checks
        IF ( @TempTable = 'NULL' AND @PermanentTable = 'NULL' )
            BEGIN
                RAISERROR ( 'ERROR: Please select a TempTable or Permanent Table.',16,1 ) 
            END

        IF ( @TempTable <> 'NULL' AND @PermanentTable <> 'NULL' )
            BEGIN
                RAISERROR ( 'ERROR: Only one table can be selected at a time. Please adjust your table selection.',16,1 ) 
            END

        IF ( @TotalColumns IS NULL )
            BEGIN
                RAISERROR ( 'ERROR: Please select a value for @TotalColumns.',16,1 ) 
            END

    --Temp table to gather the names of the columns
    IF Object_id('tempdb..#TempName') IS NOT NULL DROP TABLE #TempName
    CREATE TABLE #TempName ( ID INT, Name VARCHAR (1000) )

        --Select the column order from a temp table
        IF @TempTable <> 'NULL'
            BEGIN       
                --Verify the temp table exists
                IF NOT EXISTS ( SELECT  1 
                                FROM    tempdb.sys.columns
                                WHERE   object_id = object_id ('tempdb..' + @TempTable +'') )
                BEGIN 
                    RAISERROR ( 'ERROR: Your TempTable does not exist - Please select a valid TempTable.',16,1 ) 
                            RETURN 
                        END 

                SET @SQL = 'INSERT INTO #TempName
                            SELECT  column_id AS ID, Name 
                            FROM    tempdb.sys.columns
                            WHERE   object_id = object_id (''tempdb..' + @TempTable +''')
                            ORDER BY    column_id'
                EXEC (@SQL) 
            END

        --From a permanent table
        IF @PermanentTable <> 'NULL'
            BEGIN       
                --Verify the temp table exists
                IF NOT EXISTS ( SELECT  1
                                FROM    syscolumns
                                WHERE   id =  ( SELECT id 
                                                FROM sysobjects 
                                                WHERE Name = '' + @PermanentTable + '' ) ) 
                BEGIN 
                    RAISERROR ( 'ERROR: Your Table does not exist - Please select a valid Table.',16,1 ) 
                            RETURN 
                        END 

                SET @SQL = 'INSERT INTO #TempName
                            SELECT   colorder AS ID, Name
                            FROM     syscolumns
                            WHERE id = ( SELECT id 
                                         FROM sysobjects 
                                         WHERE Name = ''' + @PermanentTable + ''' )
                            ORDER BY colorder'
                EXEC (@SQL)
            END

        --Set the names of the columns
        IF @TotalColumns >= 1 BEGIN SET @Column1 = (SELECT Name FROM #TempName WHERE ID = 1) END
        IF @TotalColumns >= 2 BEGIN SET @Column2 = (SELECT Name FROM #TempName WHERE ID = 2) END
        IF @TotalColumns >= 3 BEGIN SET @Column3 = (SELECT Name FROM #TempName WHERE ID = 3) END
        IF @TotalColumns >= 4 BEGIN SET @Column4 = (SELECT Name FROM #TempName WHERE ID = 4) END
        IF @TotalColumns >= 5 BEGIN SET @Column5 = (SELECT Name FROM #TempName WHERE ID = 5) END

    --Create a select list of only the column names you want
    IF Object_id('tempdb..#FinalNames') IS NOT NULL DROP TABLE #FinalNames
    CREATE TABLE #FinalNames ( ID INT, Name VARCHAR (1000) )

            INSERT  #FinalNames
            SELECT  '1' AS ID, @Column1 AS Name UNION ALL
            SELECT  '2' AS ID, @Column2 AS Name UNION ALL
            SELECT  '3' AS ID, @Column3 AS Name UNION ALL
            SELECT  '4' AS ID, @Column4 AS Name UNION ALL
            SELECT  '5' AS ID, @Column5 AS Name

            --Comma Delimite the names to insert into a select statement. Bracket the names in case there are spaces 
            SELECT  @ColumnNamesAll = COALESCE(@ColumnNamesAll + '], [' ,'[') + Name
            FROM    #FinalNames
            WHERE   Name IS NOT NULL
            ORDER BY ID

            --Add an extra bracket at the end to complete the string
            SELECT  @ColumnNamesAll = @ColumnNamesAll + ']'

        --Tell the user if they selected to many columns
        IF ( @TotalColumns > 5 AND EXISTS (SELECT 1 FROM #FinalNames WHERE Name IS NOT NULL) )
            BEGIN
                SELECT 'This script has been designed for up to 5 columns' AS ERROR
                UNION ALL
                SELECT 'Only the first 5 columns have been selected' AS ERROR
            END

        IF Object_id('tempdb..#FinalNames') IS NOT NULL DROP TABLE ##OutputTable

        --Select results using only the Columns you wanted
        IF @TempTable <> 'NULL'
            BEGIN
                SET @SQL = 'SELECT  ' + @ColumnNamesAll + '
                            INTO    ##OutputTable
                            FROM     ' + @TempTable + ' 
                            ORDER BY 1'
                EXEC (@SQL)
            END

        IF @PermanentTable <> 'NULL'
            BEGIN
                SET @SQL = 'SELECT  ' + @ColumnNamesAll + '
                            INTO    ##OutputTable
                            FROM     ' + @PermanentTable + ' 
                            ORDER BY 1'
                EXEC (@SQL) 
            END

    SELECT  *
    FROM    ##OutputTable

    SET NOCOUNT OFF

答案 3 :(得分:1)

使用dynamic query的{​​{1}}也可以完成这项工作:

for xml path

答案 4 :(得分:0)

SQL不了解列的顺序。你需要知道列名才能得到它们。

您可以查看information_schema以获取列名。例如:

SELECT column_name
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE table_name = 'tbl_name'
  ORDER BY ordinal_position
  LIMIT 2;

答案 5 :(得分:0)

您可以查询表的sysobject以查找前两列,然后动态生成所需的SQL语句。

答案 6 :(得分:0)

如果你想要一个可以反复查询的permant对象,那么为每个只返回前2列的表创建一个视图。您可以将列命名为Column1和Column2,也可以使用现有名称。

如果要在没有任何预处理步骤的情况下从任何表返回前两列,请创建一个查询系统信息的存储过程,并执行从表中返回前两列的动态查询。

答案 7 :(得分:0)

  

或者我是否需要走很长的路才能找到列名?我该怎么做?

手动操作非常简单 只需先运行

select * from tbl where 1=0

此语句适用于所有主要DBMS,无需任何系统目录。 这将为您提供所有列名称,然后您需要做的就是键入前两个

select colname1, colnum2 from tbl