SELECT within variable in PROCEDURE

Asked

Viewed 695 times

5

I’m not getting the result of a select within a variable.

I want to add the column turno inside my WHERE. The problem is I get the value of @turnos in the following 3 formats:

1 - 'A'

2 - 'A','B'

3 - 'A','B','C'

Current situation

set @tjt = (select sum(duracao) from tabela where fabrica = @fabrica)

Desired situation (with error)

set @tjt= (select sum(duracao) from tabela where fabrica = @fabrica and turno IN (@turnos))

I see that turno IN (@turnos) does not work, and so I tried to put the select all between quotation marks concatenating the variables as follows:

@query = '(select sum(duracao) from tabela where fabrica = '+@fabrica+'
and turno IN ('+@turnos+'))'

But I still don’t understand how to put the result of this @query in the variable @tjt.

  • Why don’t you select within the in ()? for example ...in (select coluna from ..)?

1 answer

2


You can use the SP_EXECUTESQL with a parameter OUTPUT to obtain the desired result:

DECLARE @tjt INT;
DECLARE @query NVARCHAR(MAX);

SET @query = '(select @tjt = sum(duracao) from tabela where fabrica = ' + @fabrica + ' and turno IN (' + @turnos + '))';

EXEC SP_EXECUTESQL @query, N'@tjt INT OUT', @tjt OUT;

SELECT @tjt;
  • 1

    Deletes my previous comments in order not to confuse anyone. But the code using the SP_EXECUTESQL worked perfectly. The variable @tjt received the value of sum(duracao) as I needed. Thank you very much for the support.

  • @Daniloalex has another way of doing without having to execute string. If you inform on the question which version of SQL Server I can complement the answer

Browser other questions tagged

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