How to select all the columns of a table except one column?
I have nearly 259 columns I cant mention 258 columns in SELECT
statement.
Is there any other way to do it?
This question is related to
sql
sql-server
You can get the column name details from sys.columns table
Try the following query:
SELECT * FROM SYS.COLUMNS
WHERE object_id = OBJECT_ID('dbo.TableName')
AND [Name] <> 'ColumnName'
DECLARE @sql as VARCHAR(8000)
SET @sql = 'SELECT '
SELECT @sql += [Name] + ', ' FROM SYS.COLUMNS
WHERE object_id = OBJECT_ID('dbo.TableName')
AND [Name] <> 'ColumnName'
SELECT @sql += ' FROM Dbo.TableName'
EXEC(@sql)
You can retrieve the list of column name by simple query and then remove those column by apply where query like this.
SELECT * FROM (
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TableName'
) AS allColumns
WHERE allColumns.COLUMN_NAME NOT IN ('unwantedCol1', 'unwantedCol2')
ResultSet
to your main program or do your stuff in the same method.There are lot of options available , one of them is :
CREATE TEMPORARY TABLE temp_tb SELECT * FROM orig_tb;
ALTER TABLE temp_tb DROP col_x;
SELECT * FROM temp_tb;
Here the col_x is the column which u dont want to include in select statement.
Take a look at this question : Select all columns except one in MySQL?
Create a view. Yes, in the view creation statement, you will have to list each...and...every...field...by...name.
Once.
Then just select * from viewname
after that.
Try the following query:
DECLARE @Temp NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
SET @Temp = '';
SELECT @Temp = @Temp + COLUMN_NAME + ', ' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='Person' AND COLUMN_NAME NOT IN ('Id')
SET @SQL = 'SELECT ' + SUBSTRING(@Temp, 0, LEN(@Temp)) +' FROM [Person]';
EXECUTE SP_EXECUTESQL @SQL;
If you are using DataGrip you can do the following:
SELECT * FROM <your_table>;
*
and press Alt+Enter
Expand column list
option*
with full list of columnsIn your case, expand columns of that database in the object explorer. Drag the columns in to the query area.
And then just delete one or two columns which you don't want and then run it. I'm open to any suggestions easier than this.
Only one way to achieve this giving column name. There is no other method found. You must have to list all column name
Without creating new table you can do simply (e.g with mysqli):
$r = mysqli_query('SELECT column_name FROM information_schema.columns WHERE table_name = table_to_query');
$c = count($r); while($c--) if($r[$c]['column_name'] != 'column_to_remove_from_query') $a[] = $r[$c]['column_name']; else unset($r[$c]);
$r = mysqli_query('SELECT ' . implode(',', $a) . ' FROM table_to_query');
This is not a generic solution, but some databases allow you to use regular expressions to specify the columns.
For instance, in the case of Hive, the following query selects all columns except ds and hr:
SELECT `(ds|hr)?+.+` FROM sales
Source: Stackoverflow.com