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
Yes it's possible (but not recommended).
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')
Explanation of the code:
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.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.WHERE
clause to hide columns we don't want to see.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.