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
A colleage advised a good alternative:
Done...
This helped us a lot.
Sometimes the same program must handle different database stuctures. So I could not use a column list in the program to avoid errors in select
statements.
*
gives me all the optional fields. I check if the fields exist in the data table before use. This is my reason for using *
in select
.
This is how I handle excluded fields:
Dim da As New SqlDataAdapter("select * from table", cn)
da.FillSchema(dt, SchemaType.Source)
Dim fieldlist As String = ""
For Each DC As DataColumn In DT.Columns
If DC.ColumnName.ToLower <> excludefield Then
fieldlist = fieldlist & DC.Columnname & ","
End If
Next
Wouldn't it be simpler to do this:
sp_help <table_name>
-Click on the 'Column_name' column> Copy> Paste (creates a vertical list) into a New Query window and just type commas in front of each column value... comment out the columns you don't want... far less typing than any code offered here and still manageable.
You could create a view that has the columns you wish to select, then you can just select *
from the view...
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.That what I use often for this case:
declare @colnames varchar(max)=''
select @colnames=@colnames+','+name from syscolumns where object_id(tablename)=id and name not in (column3,column4)
SET @colnames=RIGHT(@colnames,LEN(@colnames)-1)
@colnames
looks like column1,column2,column5