我们都知道,要从表中选择所有列,可以使用

SELECT * FROM tableA

是否有一种方法可以在不指定所有列的情况下从表中排除列?

SELECT * [except columnA] FROM tableA

我所知道的唯一方法是手动指定所有列并排除不需要的列。这真的很耗时,所以我正在寻找方法来节省时间和精力,以及未来的维护表应该有更多/更少的列。


当前回答

在SSMS中,智能感知和混叠是一种更简单的方法。试试这个 在文本编辑器中右键单击,并确保启用了智能感知。 输入一个别名[SELECT t.* FROM tablename t]的查询。 输入文本t.*并删除*,SSMS将自动列出以f为别名的表的列。 然后,您可以快速指定您想要的列,而不必使用SSMS将选择写入另一个脚本,然后执行更多的复制/粘贴操作。 我一直在用这个。

其他回答

总之,你不能这样做,但我不同意上面所有的评论,有“一些”情况下,你可以合法地使用* 当您创建一个嵌套查询以便从整个列表中选择一个特定的范围(例如分页)时,为什么要在外部选择语句中指定每一列,而您已经在内部选择语句中完成了呢?

是的,这是可能的(但不建议)。

CREATE TABLE contact (contactid int, name varchar(100), dob datetime)
INSERT INTO contact SELECT 1, 'Joe', '1974-01-01'

DECLARE @columns varchar(8000)

SELECT @columns = ISNULL(@columns + ', ','') + QUOTENAME(column_name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'contact' AND COLUMN_NAME <> 'dob'
ORDER BY ORDINAL_POSITION

EXEC ('SELECT ' + @columns + ' FROM contact')

代码说明:

Declare a variable to store a comma separated list of column names. This defaults to NULL. Use a system view to determine the names of the columns in our table. Use SELECT @variable = @variable + ... FROM to concatenate the column names. This type of SELECT does not not return a result set. This is perhaps undocumented behaviour but works in every version of SQL Server. As an alternative you could use SET @variable = (SELECT ... FOR XML PATH('')) to concatenate strings. Use the ISNULL function to prepend a comma only if this is not the first column name. Use the QUOTENAME function to support spaces and punctuation in column names. Use the WHERE clause to hide columns we don't want to see. Use EXEC (@variable), also known as dynamic SQL, to resolve the column names at runtime. This is needed because we don't know the column names at compile time.

你可以这样尝试:

/* Get the data into a temp table */
SELECT * INTO #TempTable
FROM YourTable
/* Drop the columns that are not needed */
ALTER TABLE #TempTable
DROP COLUMN ColumnToDrop
/* Get results and drop temp table */
SELECT * FROM #TempTable
DROP TABLE #TempTable

如果你使用的是PHP,你只需要查询,然后你可以取消设置一个特定的元素:

$sql = "SELECT * FROM ........ your query";
    $result = $conection->query($sql); // execute your query
    $row_cnt = $result->num_rows;   

if ($row_cnt > 0) {
        while ($row = $result->fetch_object()) {
            unset($row->your_column_name); // Exclude column from your fetch
            $data[] = $row;
}
echo json_encode($data); // or whatever

在SQL Management Studio中,您可以展开对象资源管理器中的列,然后将columns树项拖到查询窗口中,以获得以逗号分隔的列列表。