I have a table where I have columns like below
[Index], [Length],[N1],[N2]....[N99]
Now, is possible to select only [N2]] ... [N29]
columns without writing all names.
I have a table where I have columns like below
[Index], [Length],[N1],[N2]....[N99]
Now, is possible to select only [N2]] ... [N29]
columns without writing all names.
No, it's not possible. You need to explicitly list the subset of columns you want to return.
You can of course drag and drop all the columns from the object browser and then delete the ones you don't want. At least that way you don;t have any typos.
I would be concerned about the design of a table with that many columns. Espceially if they really are N1-N99. You may need a redesign to a related table. Also wide tables can cause performance issues.
Using dynamic sql is the closest you can get to not writing the columns. Here is an example:
declare @sql varchar(max)
select @sql = coalesce(@sql+',', 'select ') + 'n' + cast(number as varchar(2))
from master..spt_values as N
where type = 'P' and
number between 2 and 29
set @sql = @sql + ' from <yourtable>'
--select @sql
exec (@sql)
How about this:
DECLARE @columns VARCHAR(MAX),
@tablename VARCHAR(255),
@from VARCHAR(255),
@select VARCHAR(100)
SET @tablename = 'orderheader'
SELECT @columns = STUFF(
(
SELECT ',[' + column_name + ']'
FROM information_schema.columns
WHERE table_name = @tablename
AND NOT column_name IN ('N2', 'Index', 'Length')
FOR XML PATH('')
),1, 1, '')
SELECT @select = 'SELECT ', @from = ' from ' + @tablename
EXEC(@select + @columns + @from)