Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Script Library
 Select Data from Top N Columns

Author  Topic 

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-08-08 : 09:10:36
Suppose you have table with many columns and often you need data from first 15 or 20 columns. In that case you have to specify all the columns in your select statement. This procedure will select top N columns you want. All you have to do is to supply table name and number of columns you want

Here is the procedure



Create procedure TopNcolumns (@tableName varchar(100),@n int)
as
Declare @s varchar(2000)
set @s=''
If exists(Select * from information_Schema.tables where table_name=@tablename and table_type='Base Table')
Begin
If @n>=0
Begin
set rowcount @n
Select @s=@s+','+ column_name from information_schema.columns
where table_name=@tablename order by ordinal_position
Set rowcount 0
Set @s=substring(@s,2,len(@s)-1)
Exec('Select '+@s+' from '+@tablename)
End
else
Select 'Negative values are not allowed' as Error
End
else
Select 'Table '+@tableName+' does not exist' as Error



Madhivanan

Failing to plan is Planning to fail

maya_zakry
Constraint Violating Yak Guru

379 Posts

Posted - 2007-01-09 : 02:53:21
hi madhivanan,

how do we use this SP after we created it? method of use?
how about we dont want to select first top, we want to select any column from 1 to 100? can this be achieved using this function? thanks.
-newbie-
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-10-12 : 02:29:42
quote:
Originally posted by maya_zakry

hi madhivanan,

how do we use this SP after we created it? method of use?
how about we dont want to select first top, we want to select any column from 1 to 100? can this be achieved using this function? thanks.
-newbie-


I wonder how I missed out to notice your question

You need to add where clause to include/exclude the colids

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2007-10-12 : 03:12:32
"I wonder how I missed out to notice your question"

I thought it was just me ... I have had several threads that I missed in Active Topics a few weeks ago. I thought it was just me, but I can't remember it happening before, and it seems to have stopped again!

Kristen
Go to Top of Page
   

- Advertisement -