I have the following 2 queries that should return the same information.
One normal query and the dynamic query which does not retrieve any result because of the @TABLENAME variable naming I guess.
DECLARE @TABLENAME as NVARCHAR (MAX) SET @TABLENAME = 'MyTable' Query Returning Results
select * from jfa.[dbo].[MyTable] INNER JOIN INFORMATION_SCHEMA.COLUMNS on INFORMATION_SCHEMA.COLUMNS.TABLE_NAME = @TableName and INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION = 2 Dynamic Query that does not return any result
DECLARE @sql as nvarchar(max) set @sql = 'select * from jfa.[dbo].[MyTable] INNER JOIN INFORMATION_SCHEMA.COLUMNS on INFORMATION_SCHEMA.COLUMNS.TABLE_NAME = ''@TableName'' and INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION = 2' exec sp_executeSQL @sql, N'@TABLENAME nvarchar', @TABLENAME I guess the problem is in the following line:
on INFORMATION_SCHEMA.COLUMNS.TABLE_NAME = ''@TableName'' But I have tried several things an no success.
Many thanks in advance,
Kat