C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Interview   Jobs   Projects   Offshore Development    
Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing | Talk to Us |



My Profile

Gifts

Active Members
TodayLast 7 Days more...







How to select TOP N number of columns


Posted Date: 12 Jun 2008    Resource Type: Code Snippets    Category: SQL

Posted By: ashwin       Member Level: Bronze
Rating:     Points: 10



Often there is a requirement that you donot want all columns to be in your select query. For example, if your table has 35 columns and you need to get only 15 columns, then, yo have to specify every column name in your query. Following Stored Procedure helps in fetching top N columns from table. All it requires is table name and number of columns you need in your select statement.


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





Responses

Author: Kapil Dhawan    16 Jun 2008Member Level: Gold   Points : 1
Hello,
Nice piece of Code.
Thanks for sharing your knowledge with us.

Regards,
Kapil


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Selectcolumn  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: How to format date in MS SQL
Previous Resource: Different ways of deleting duplicate records in a table.
Return to Discussion Resource Index
Post New Resource
Category: SQL


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

doors in nj

Contact Us    Privacy Policy    Terms Of Use