我们都知道,要从表中选择所有列,可以使用
SELECT * FROM tableA
是否有一种方法可以在不指定所有列的情况下从表中排除列?
SELECT * [except columnA] FROM tableA
我所知道的唯一方法是手动指定所有列并排除不需要的列。这真的很耗时,所以我正在寻找方法来节省时间和精力,以及未来的维护表应该有更多/更少的列。
我们都知道,要从表中选择所有列,可以使用
SELECT * FROM tableA
是否有一种方法可以在不指定所有列的情况下从表中排除列?
SELECT * [except columnA] FROM tableA
我所知道的唯一方法是手动指定所有列并排除不需要的列。这真的很耗时,所以我正在寻找方法来节省时间和精力,以及未来的维护表应该有更多/更少的列。
当前回答
在SQL (SQL Server)中自动做到这一点的方法是:
declare @cols varchar(max), @query varchar(max);
SELECT @cols = STUFF
(
(
SELECT DISTINCT '], [' + name
FROM sys.columns
where object_id = (
select top 1 object_id from sys.objects
where name = 'MyTable'
)
and name not in ('ColumnIDontWant1', 'ColumnIDontWant2')
FOR XML PATH('')
), 1, 2, ''
) + ']';
SELECT @query = 'select ' + @cols + ' from MyTable';
EXEC (@query);
其他回答
在SQL (SQL Server)中自动做到这一点的方法是:
declare @cols varchar(max), @query varchar(max);
SELECT @cols = STUFF
(
(
SELECT DISTINCT '], [' + name
FROM sys.columns
where object_id = (
select top 1 object_id from sys.objects
where name = 'MyTable'
)
and name not in ('ColumnIDontWant1', 'ColumnIDontWant2')
FOR XML PATH('')
), 1, 2, ''
) + ']';
SELECT @query = 'select ' + @cols + ' from MyTable';
EXEC (@query);
不,这是不可能的。如果在您的情况下可行,也许您可以创建自定义视图
如果你的数据库支持动态sql的执行,你可以写一个SP,把你不想看到的列传递给它,让它动态创建查询并返回结果给你。我认为这至少在SQL Server中是可行的
你可以这样尝试:
/* 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
如果您正在使用SQL Server Management Studio,那么请执行以下操作:
输入所需的表名并选择它 按Alt + F1 O /p表示表中的列。 选择所需的列 复制并粘贴这些在您的选择查询 触发查询。
享受。
是的,这是可能的(但不建议)。
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.