Database objects as Stored Procedure parameters

Asked

Viewed 87 times

3

Why when we pass database objects as parameters in a stored database they are not accepted?

Ex:

@COLUNA nvarchar(30),
@VARIAVEL nvarchar(50)
SELECT * FROM TBL_TESTE WHERE @COLUNA = @VARIAVEL

The only alternative would be dynamic consultations?

2 answers

0


SQL Server does not concatenate commands only values, so you can pass values for a command to be mounted and run, Example:

@COLUNA nvarchar(30),
 @VARIAVEL nvarchar(50)

declare @CMD varchar(4000)

set @CMD = 'SELECT * FROM TBL_TESTE WHERE '+@COLUNA+' = '+@VARIAVEL+''
 exec sp_executeSQL @CMD 

If you still have doubts let me know

-2

declare
    @campo varchar(50),
    @valor varchar(50),
    @qry   varchar(max)

set @campo = 'Inscricao';
set @valor = '123456';
set @qry = 'select * from tabela where ' + @inscricao + ' = ' + @valor;

Exec (@qry)
  • 1

    Could explain what this code does?

  • Hello Marcela, welcome to [en.so]! Here on the site users usually value objective answers and explain what is being done. For example, you only provided a code, but you answered exactly what you were asked. These were probably the reasons for the negatives the reply received. It would be interesting if you could edit your reply to add a few comments above. Hug!

Browser other questions tagged

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