Query

除選定的所有列

  • March 27, 2019

是否可以為單個表選擇除少數欄位之外的所有欄位?(假設有一堆欄位在 Select 語句中寫入每個欄位是耗時的)。

id  row_num  customer_code comments
-----------------------------------
1   1        Dilbert        Hard
1   2        Dilbert        Worker
2   1        Wally          Lazy

就像是:

Select * Except (row_num) from Table 

上面的語法是錯誤的,因為我得到一個錯誤“select * must have a from 子句”

那麼獲得輸出的適當語法是什麼:

id  customer_code comments
-----------------------------------
1   Dilbert        Hard
1   Dilbert        Worker
2   Wally          Lazy

您可以創建儲存過程並使用動態 SQL 和 INFORMATION_SCHEMA 表來動態生成 SELECT 語句。

儲存過程:

CREATE PROCEDURE spGenerateSelect (@SchemaName NVARCHAR(255), 
   @TableName NVARCHAR(255),
   @ExcludeColumns NVARCHAR(MAX)
)
AS
BEGIN

   SELECT @ExcludeColumns = '''' + REPLACE(@ExcludeColumns, ', ', ''', ''') + ''''

   DECLARE @SqlCmd NVARCHAR(MAX),
       @ParamDefinition NVARCHAR(MAX),
       @ColumnsOut NVARCHAR(MAX)

   SET @ParamDefinition = '@SchemaName NVARCHAR(255), @TableName NVARCHAR(255), @Columns NVARCHAR(MAX) OUTPUT'

   SET @SqlCmd = 'SELECT @Columns = COALESCE(@Columns + '', '', '''') + QUOTENAME(c.COLUMN_NAME)
   FROM INFORMATION_SCHEMA.COLUMNS c
   INNER JOIN INFORMATION_SCHEMA.TABLES t ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
   WHERE t.TABLE_SCHEMA = @SchemaName AND t.TABLE_NAME = @TableName AND c.COLUMN_NAME NOT IN (' + @ExcludeColumns + ');'

   EXEC sp_executesql @SqlCmd, @ParamDefinition, @SchemaName = @SchemaName, @TableName = @TableName, @Columns = @ColumnsOut OUTPUT

   SELECT 'SELECT ' + @ColumnsOut + ' FROM ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName)
END

執行:

EXEC spGenerateSelect @SchemaName = 'dbo', @TableName = 'SubjectPeriod', @ExcludeColumns = 'SubjectID, TeacherID'

這將為所有列輸出一個 SELECT 語句,不包括 @ExcludeColumns 中提供的那些,這是一個以逗號分隔的要排除的列名列表。

引用自:https://dba.stackexchange.com/questions/233203