Select columns from the records of another table

1

I have a question that I have not yet been able to solve.

It turns out that I want to select the fields in a table. The problem is that these fields are not fixed but are stored in another table 'Table1'

SELECT Campos FROM Tabla1

Campos
------
Col1
Col2
Col3

From these registers I want to form a string that allows me to select the fields obtained from the other table.

Like this:

SELECT Col, Col2, Col3 FROM Cuentas
    
asked by Freddy 15.06.2017 в 19:23
source

1 answer

0

What you need is to arm a sentence dynamically to get the bosses you want. With dynamic sentences you have to be careful in two things, on the one hand you have to take into account that we lose the possibility that the engine optimizes the query as it usually happens with normal queries, and on the other hand you have to be careful as they are sentences where you could easily inject code.

As proof of concept:

-- Tabla de campos
DECLARE @TablaCampos TABLE (
    Campo   VARCHAR(255)
)

INSERT INTO @TablaCampos (Campo)
SELECT  'id'    UNION
SELECT  'name'

DECLARE @SQL NVARCHAR(MAX)

-- Armo el select dinámico con los campos prefijados
SELECT  @SQL = 'SELECT  '
SELECT  @SQL = @SQL + Campo + ','
    FROM @TablaCampos

SELECT  @SQL = left(@SQL, LEN(@SQL) - 1) + ' FROM sysobjects'

-- Ejecuto la sentencia dinámica
EXEC sp_executesql @SQL
    
answered by 15.06.2017 / 19:38
source