SQL Server How to link the name of a column to an external variable?

Asked

Viewed 24 times

-2

Good morning Srs

I made an SQL code that separates an item from each record from a column without repeating, and is working correctly, follows code below:

SELECT Tab_Dados_Escolha.Nome_Produto FROM Tab_Dados_Escolha
GROUP BY Tab_Dados_Escolha.Nome_Produto

but I would like to replace the column name where this routine will be done with an external variable, so I could use this same code for the other columns without having to rewrite another code and I’m not getting it so far, someone can help me?

Thanks in advance

1 answer

0

Dude, that’s it, just put the database name (not required) and run

declare @comando varchar(max),
        @tabela varchar(max),
        @coluna varchar(max),
        @database varchar(max)

set @tabela = 'Tab_Dados_Escolha'
set @coluna = 'Nome_Produto '
set @database = ''

set @comando = 'SELECT '+@tabela+'.'+@coluna+',count(*) as quantidade FROM '+@database+'.dbo.'+@tabela+' GROUP BY '+@tabela+'.'+@coluna

exec(@comando)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.