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
 New to SQL Server Programming
 Another way to write this query

Author  Topic 

ahmeds08
Aged Yak Warrior

737 Posts

Posted - 2013-02-05 : 12:59:21
Dear Experts,
Below query lists out all the tables and their respective column names as field list.
how can i achieve the same output without using cursor,loops and temp objects.

declare @ColName sysname,
@TableName sysname,
@FieldList varchar(MAX),
@LastTableName sysname

select @LastTableName = '',

@FieldList = ''

declare @tb table (TableName sysname null, FieldList varchar(MAX) null)
declare curs cursor for

select c.name, object_name(c.object_id)

from sys.columns c INNER JOIN sys.objects o on c.object_id = o.object_id

where o.type = 'U'

order by o.object_id

open curs

fetch curs into @ColName, @TableName

set @LastTableName = @TableName

while @@FETCH_STATUS = 0

BEGIN
if @LastTableName<> @TableName

BEGIN

insert into @tb values (@LastTableName,@FieldList)

set @FieldList = ''
set @LastTableName = @TableName

END



set @FieldList = case when @FieldList = '' then @ColName else + @FieldList + ',' + @ColName end



fetch curs into @ColName, @TableName

END

deallocate curs

insert into @tb values (@LastTableName,@FieldList)

select * from @tb

Thanks,
Javeed

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-02-05 : 13:11:43
looks like this to me

SELECT t.TABLE_NAME,
STUFF((SELECT ',' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = t.TABLE_NAME FOR XML PATH('')),1,1,'')
FROM INFORMATION_SCHEMA.TABLES t
WHERE t.TABLE_TYPE='BASE TABLE'


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

ahmeds08
Aged Yak Warrior

737 Posts

Posted - 2013-02-05 : 13:25:01
Visakh,
Thanks a lot.


quote:
Originally posted by visakh16

looks like this to me

SELECT t.TABLE_NAME,
STUFF((SELECT ',' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = t.TABLE_NAME FOR XML PATH('')),1,1,'')
FROM INFORMATION_SCHEMA.TABLES t
WHERE t.TABLE_TYPE='BASE TABLE'


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/



Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-02-06 : 00:56:33
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -