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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Getting table name as part of result set

Author  Topic 

jeffnc
Starting Member

14 Posts

Posted - 2008-10-20 : 11:06:09
I have a simple dynamic query that looks like
SET @Sql = 'SELECT [' + @column + '] FROM [' + @table + ']'
EXEC(@Sql)

Is there a way I could get the actual table name to show up as part of the result? What I want to do (but of course this won't work) is
SET @Sql = 'SELECT [' + @table +'],[' + @column + '] FROM [' + @table + ']'

This is for user viewed output.

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-10-20 : 11:13:52
SET @Sql = 'SELECT ''' + @table +''' as table_name,[' + @column + '] FROM [' + @table + ']'

Madhivanan

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

jeffnc
Starting Member

14 Posts

Posted - 2008-10-20 : 13:49:46
quote:
Originally posted by madhivanan

SET @Sql = 'SELECT ''' + @table +''' as table_name,[' + @column + '] FROM [' + @table + ']'



I'm sure you meant

SET @Sql = 'SELECT ''' + @column +''' as table_name,[' + @column + '] FROM [' + @table + ']'

Thanks!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-20 : 13:59:57
quote:
Originally posted by jeffnc

quote:
Originally posted by madhivanan

SET @Sql = 'SELECT ''' + @table +''' as table_name,[' + @column + '] FROM [' + @table + ']'



I'm sure you meant

SET @Sql = 'SELECT ''' + @column +''' as table_name,[' + @column + '] FROM [' + @table + ']'

Thanks!


Nope first one is @table itself. He's returning tablename itself as first column which is what OP wants.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-10-21 : 03:31:00
quote:
Originally posted by jeffnc

quote:
Originally posted by madhivanan

SET @Sql = 'SELECT ''' + @table +''' as table_name,[' + @column + '] FROM [' + @table + ']'



I'm sure you meant

SET @Sql = 'SELECT ''' + @column +''' as table_name,[' + @column + '] FROM [' + @table + ']'

Thanks!


Run and see


Madhivanan

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

LoztInSpace
Aged Yak Warrior

940 Posts

Posted - 2008-10-21 : 08:12:16
WTF would you even want to do this?
Go to Top of Page
   

- Advertisement -