I'm using the sp_MSForeachtable
to retrieve the columnames of all tables and concatenating the columnames in a single string. I'm using the following query. I've executed the same providing the parameter through a variable for a single table and works perfectly, but when executed from the SP it fails with the error 'The multi-part identifier "dbo.TableNm" could not be bound.'
DECLARE @query nvarchar(max)
SELECT @query =
'DECLARE @Names VARCHAR(255)
DECLARE @DB VARCHAR(255)
SELECT @Names = COALESCE(@Names + '', '', '''') + COLUMN_NAME FROM Information_Schema.COLUMNS
WHERE TABLE_NAME = ?
SELECT TOP 1 @DB = TABLE_CATALOG FROM Information_Schema.COLUMNS
WHERE TABLE_NAME = ?
SELECT @DB AS [DataBase], ? AS [Table], @Names AS [Columns]'
EXEC sp_MSforeachtable @query
I thought the error might be associated with having multiple tables with the same name in different databases so I tried pre-fixing the database but i still get the same error.
DECLARE @query nvarchar(max)
SELECT @query =
'DECLARE @Names VARCHAR(255)
DECLARE @DB VARCHAR(255)
DECLARE @TableNm VARCHAR(255) = ?
SET @DB = ''People_Directory''
SELECT @Names = COALESCE(@Names + '', '', '''') + COLUMN_NAME FROM Information_Schema.COLUMNS
WHERE TABLE_NAME = @TableNm
AND TABLE_CATALOG = @DB
SELECT @DB AS [DataBase], @TableNm AS [Table], @Names AS [Columns]'
EXEC sp_MSforeachtable @query
I'll keep trying bu I'm running out of ideas. Any thoughts?