SQL Dynamic SELECT statement from values ​​stored in a table.

I have been studying this for several days and feel like I'm going in circles. I have basic knowledge of SQL, but there are many areas that I do not understand.

I have a table that stores the names and fields of all other tables in my database.

tblFields
===================================================

TableName      FieldName     BookmarkName  
---------------------------------------------------
Customer       FirstName     CustomerFirstName  
Customer       LastName      CustomerLastName  
Customer       DOB           CustomerDOB  

I want to write an instruction SELECTas shown below, but I cannot get it to work:

SELECT (SELECT [FieldName] FROM [TableName]) FROM tblFields

Is it possible? For the application I developed, this is required for customizing reports.

+3
source share
2 answers

, , , , . , , , , , .

SQL, , . SQL Server, , sp_executesql. SQL.

+1

, , , . , SQL Server 2005 , , , , :

declare @tableName nvarchar(100)
declare @sqlQuery nvarchar(max)
declare @fields varchar(500)
set @tableName = 'YourTableName'
set @fields = ''
select @fields = @fields + QUOTENAME(t.fieldname) + ',' from (
select distinct fieldname from tblfields where tablename = @tableName)t


set @sqlQuery = 'select ' + left(@fields, LEN(@fields)-1) + ' from ' + QUOTENAME(@tableName)

execute sp_executesql @sqlQuery

: , , QUOTENAME

+1

Source: https://habr.com/ru/post/1796625/


All Articles