SQL exclude a column using SELECT * [except columnA] FROM tableA?

后端 未结 30 2589
花落未央
花落未央 2020-11-21 23:15

We all know that to select all columns from a table, we can use

SELECT * FROM tableA

Is there a way to exclude column(s) from a table witho

30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 00:04

    DECLARE @SQL VARCHAR(max), @TableName sysname = 'YourTableName'
    
    SELECT @SQL = COALESCE(@SQL + ', ', '') + Name 
    FROM sys.columns
    WHERE OBJECT_ID = OBJECT_ID(@TableName)
    AND name NOT IN ('Not This', 'Or that');
    
    SELECT @SQL = 'SELECT ' + @SQL + ' FROM ' + @TableName
    
    EXEC (@SQL)
    

    UPDATE:

    You can also create a stored procedure to take care of this task if you use it more often. In this example I have used the built in STRING_SPLIT() which is available on SQL Server 2016+, but if you need there are pleanty of examples of how to create it manually on SO.

    CREATE PROCEDURE [usp_select_without]
    @schema_name sysname = N'dbo',
    @table_name sysname,
    @list_of_columns_excluded nvarchar(max),
    @separator nchar(1) = N','
    AS
    BEGIN
     DECLARE 
     @SQL nvarchar(max),
     @full_table_name nvarchar(max) = CONCAT(@schema_name, N'.', @table_name);
    
     SELECT @SQL = COALESCE(@SQL + ', ', '') + QUOTENAME([Name])
     FROM sys.columns sc
     LEFT JOIN STRING_SPLIT(@list_of_columns_excluded, @separator) ss ON sc.[name] = ss.[value]
     WHERE sc.OBJECT_ID = OBJECT_ID(@full_table_name, N'u')
     AND ss.[value] IS NULL;
    
     SELECT @SQL = N'SELECT ' + @SQL + N' FROM ' + @full_table_name;
     EXEC(@SQL)
    END
    

    And then just:

    EXEC [usp_select_without] 
    @table_name = N'Test_Table',
    @list_of_columns_excluded = N'ID, Date, Name';
    

提交回复
热议问题