Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi every,

I would like to do dynamic querying in a store procedure... I have a table which will store Table_Name and Field_Name With name tblConfig

Select * from tblConfig where id = @id

will give Table_Name(like tblUser) and Field_Name(like CID)

Now i want to select above Field_Name from above Table_Name and out put the result,
something like select (returned Field_Name) as fld_data from (returned Table_Name) in a store procedure.

So, Any help or an idea about this will be highly appreciated.

Thanks.
Posted
Updated 25-Nov-14 18:59pm
v2

Try following SQL
SQL
DECLARE @DynamicQuery AS NVARCHAR(MAX)
DECLARE @ColNames AS NVARCHAR(MAX)
DECLARE @TblName AS NVARCHAR(MAX)
SELECT @ColNames= ISNULL(@ColNames + ',','')+ QUOTENAME(Field_Name) FROM (Select Field_Name from tblConfig Where id =1/*@id*/) as fld_data
SELECT @TblName = Table_Name FROM (Select Table_Name from tblConfig Where id =1/*@id*/) as tbl_data
Print @ColNames
Print @TblName
SET @DynamicQuery =  N' Select ' + @ColNames + '   from ' + @TblName + ' ';
EXEC sp_executesql @DynamicQuery
 
Share this answer
 
v2
Comments
Tomas Takac 26-Nov-14 4:11am    
+5 for handling multiple columns, although I think you could get @ColNames and @TblName in one query and without the subquery
SQL
declare @TableName nvarchar(50)
declare @FieldName nvarchar(50)
declare @Qry nvarchar(max)
set @TableName=(select Table_Name from tblConfig where id = @id)
set @FieldName=(select Field_Name from tblConfig where id = @id)

set @Qry=('select '+@FieldName ' from '+@TableName)
exec(@Qry)
 
Share this answer
 
you may refer to this

SQL
Create Proc GetValues(@ID as int)
As
BEGIN
    Declare @SQL Nvarchar(max),@table nvarchar(30),@fieldname nvarchar(30)

select @table=table,@field name=fieldname from tblconfig where id=@ID

    set @SQL='select '+@field name+' from '+@table 

    exec Sp_Execute @SQL
END
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900