Return fields from parameters

2

Good evening,

I need the return of a SELECT to be dependent on the parameter that is passed in SELECT

Example declare @variavel nvarchar (50)

Select          field          campob,          campoc,          campod,          campoe,

from table

I need to be:

@variaval = campoa return: select field, fieldb from table

if

@variavel = campob return: select fieldb, campoc, campod from table

How to make this logic?

    
asked by anonymous 03.05.2016 / 02:56

1 answer

1

I believe this is what you need.

DECLARE @Variavel AS VARCHAR(MAX); DECLARE @ComandoSQL AS VARCHAR(MAX);
SET @Variavel = 'campoa';

IF (@Variavel = 'campoa')
    BEGIN 
        SET @ComandoSQL = 'SELECT campoa, campob, campoc, campod, campoe FROM Tabela' 
    END 
ELSE IF (@Variavel = 'campob')
    BEGIN 
        SET @ComandoSQL = 'SELECT campob, campoc, campod FROM Tabela'
    END 

/*Mostra o comando sql gerado*/
SELECT @ComandoSQL

/*Executa o comando sql gerado*/
EXEC (@ComandoSQL)
    
13.07.2016 / 16:02