I would like to know, how to include a variable as a part of a SQL statement, to clarify more about my question, here is the code
declare @PartNo as nvarchar(20)
declare @PPFno as nvarchar(20)
declare @Dimension as nvarchar(30)
declare @cursor CURSOR
declare @colname as nvarchar(30)
declare @top as integer
declare @query as nvarchar(MAX)
declare @categoryid NVARCHAR(MAX)
set @cursor = CURSOR FOR
(select [Name] from sys.columns where object_id = (select object_id from sys.tables where name = 'ProductProperty') and [Name] like 'T%' and [name] <> 'TEMP')order by [Name] asc
OPEN @cursor
FETCH NEXT
FROM @cursor INTO @colname
WHILE @@FETCH_STATUS = 0
BEGIN
--set @query = (select @colname from ProductProperty where PartNo = @PartNo and PPFNo = @PPFno )
--set @query = 'select distinct '+@colname+' from ProductProperty where PartNo = '''+@PartNo+''' and PPFNo = '''+@PPFno+''' and DName = '''+@Dimension+''''
BEGIN
EXEC sp_executesql N'set @categoryid = (select distinct @colname from ProductProperty where PartNo = @PartNo and PPFNo = @PPFno and DName = @Dimension)',
N'@colname nvarchar(30), @PartNo nvarchar(20), @PPFno nvarchar(20),@Dimension nvarchar(30), @categoryid NVARCHAR(MAX) OUTPUT', @colname,@PartNo, @PPFno,@Dimension, @categoryid OUTPUT
select @categoryid,@colname ,@PartNo
END
--end
FETCH NEXT
FROM @cursor INTO @colName
END
CLOSE @cursor
DEALLOCATE @cursor
Please do take note I did not included the variable types. I would just want to know how can @colname become part of the SQL Statement.
To Elaborate more. Using this code, I am receiving this data
Where T1 is the table name. I want to create a query where I could pass table names into a variable, then retrieve the contents of that query.
So the SQL Query should look like this:
select T1 from ProductProperty
But I am not receiving the query, instead, I am receiving the variable data, which is in the screenshot above.
The problem is, if you might notice in my code, I have the variable @categoryid as a output parameter. This is to check the contents of the query.
it seems like I am producing a query which looks like this
select 'T1' from ProductProperty
May I ask, what am I doing wrong? If you would want additional information, please do tell me.
EDIT:
completed the query for more clarification

select T1 from table, with the parameters and all, I can retreive the data that I wanted.select distinct ' + @colname + ' from...(watch out for SQL injection vulnerability though, depending on the source of@colname)