That was similar to what I had come up with but I like your approach better. I had never seen the QuoteName function before and it works pretty well.
What I am trying to do is try to return the values in certain reference tables. I don't know what the name of the tables are - this is dynamic. The "Tables" table have a list of reference tables in them that I can use for dropdowns in my application. The record would have the 4 columns, PK, Table name, name of the PK in the table, and the name of the column that has the text that we want to show in the dropdown.
So what I wanted to do is call a stored procedure that will send back the records from all the tables that are in the "Tables" table.
I had come up with:
********************************************
DECLARE @sql varchar(8000)
SELECT @sql = ' SELECT ''' + ForeignKeyTable + ''' AS TableName, '
+ ForeignKeyField + ' AS Value , '
+ ForeignKeyValueField + ' AS Text'
+ ' FROM ' + ForeignKeyTable
+ ' Order By TableName, Value'
FROM Tables
SELECT @sql
EXEC (@sql)
*************************************************
I was trying to see if there was a way to do this without using cursors or dynamic SQL.
Yours is similar but you use the Coalesce and QuoteName which I like better. So I changed it to this which works pretty well.
*******************************************
declare @SQL nvarchar(max)
select @SQL = coalesce(@SQL + ' UNION ALL ','')
+ 'SELECT ''' + QUOTENAME(ForeignKeyTable)
+ ''', ' + QUOTENAME(ForeignKeyField)+ ', '
+ QUOTENAME(ForeignKeyValueField)
+ ' from ' + quotename(ForeignKeyTable)
from Tables
***********************************************
What I am not sure about is that the main difference between yours and mine on the table and column names is that you send them to the QuoteName function.
What does that do for you that just using the name doesn't?
Thanks,
Tom