SQL IN @Variable

Explico mi problema a continuación:
Tengo un procedimiento en el cual necesito buscar un dato con el comando IN dentro de un listado, este listado es una variable varchar @FLOTAS, pero al intentar ejecutar el código no me resulta diciéndome que hay un error de sintaxis cerca de @FLOTAS. Adjunto código:
...
DECLARE @FLOTAS as varchar(1000)
SET @FLOTAS ='(''CAM332'',''CAM333'',''CAM334'',''CAM335'')'
SELECT
  hist_statusevents.eqmt AS Equipo,
    hist_statusevents.shiftindex AS Turno,
    hist_statusevents.starttime AS Segundo_Inicio,
  hist_statusevents.endtime As Segundo_Termino,
    hist_statusevents.category AS Categoria
INTO
    #detalle_tiempos_equipos
FROM
    hist_statusevents
WHERE
    (hist_statusevents.shiftindex BETWEEN @STARTD AND @ENDD) AND
    (hist_statusevents.eqmt IN @FLOTAS) -- Aquí el error
ORDER BY
  #detalle_tiempos_equipos.Equipo,
  #detalle_tiempos_equipos.Turno,
  #detalle_tiempos_equipos.Segundo_Inicio ASC
...
¿Se puede hacer? ¿Estoy utilizando el tipo de datos correcto? Si fuera un procedimiento almacenado me aceptaría el paso de un string por VB.NET hacia el parámetro @FLOTAS?

2 Respuestas

Respuesta
1
Es correcto lo que pones, pero te sugiero que en vez de usar IN uses =
esto es asumiendo que el valor asignado a @FLOTAS es unico, por ejemplo 5, de no ser asi, y ser una cadena del tipo "2, 3, 4" eso si no se podira hacer, para ese caso te recomendaria que uses la sentencia exec(@SQL)  donde @SQL es una variable del tipo NVARCHAR y seria asi
set @SQL= 'select .... from ... where eqrnt= '+ @FLOTAS    (aca si es valida tu cadena)
Exec (@SQL)
Gracias Brownsea, he dado con la solución pero lo que me planteas está muy bueno y creo que probaré también tu solución para compararla con la mía.
Lo que finalmente hice fue procesar la cadena @FLOTAS y poner cada elemento de ese listado en una tabla temporal (ese era mi problema, @FLOTAS es un listado y no un valor único) y luego hacer un JOIN de esta tabla con la tabla desde donde quería sacar los valores. Quedo algo así:
DECLARE @FLOTAS as varchar(1000)
DECLARE @EQUIPO as varchar(15)
DECLARE @EQUIPO2 as varchar(15)
-- Parámetros
SET @STARTD = 28368
SET @ENDD = 28427
SET @FLOTAS = '(''CAM332'',''CAM333'',''CAM334'',''CAM335'')'
SET @FLOTAS = REPLACE(@FLOTAS,')','')
SET @FLOTAS = REPLACE(@FLOTAS,'(','')
SET @FLOTAS = REPLACE(@FLOTAS,'''','')
CREATE TABLE #Flotas (Equipos varchar(10))
WHILE LEN(@FLOTAS) > 0
  BEGIN
   IF CHARINDEX(',', @FLOTAS) > 0
      SET @EQUIPO = LEFT(@FLOTAS, PATINDEX('%_[,]%', @FLOTAS))
    ELSE
      SET @EQUIPO = @FLOTAS
    SET @EQUIPO2 = @EQUIPO + ','
    INSERT INTO #Flotas VALUES (@EQUIPO)
    SET @FLOTAS = REPLACE(@FLOTAS,@EQUIPO,'')
    IF CHARINDEX(',', @FLOTAS) > 0
      SET @FLOTAS = STUFF(@FLOTAS, 1,1,'')
    ELSE
        SET @FLOTAS = REPLACE(@FLOTAS,@EQUIPO,'')
  END    
SELECT
  hist_statusevents.eqmt AS Equipo,
    hist_statusevents.shiftindex AS Turno,
    hist_statusevents.starttime AS Segundo_Inicio,
  hist_statusevents.endtime As Segundo_Termino,
    hist_statusevents.category AS Categoria,
  hist_statusevents.reason as Razon
INTO
    #detalle_tiempos_equipos
FROM
    hist_statusevents join #Flotas on hist_statusevents.eqmt = #Flotas.Equipos
WHERE
    (hist_statusevents.shiftindex BETWEEN @STARTD AND @ENDD)
ORDER BY
  #detalle_tiempos_equipos.Equipo,
  #detalle_tiempos_equipos.Turno,
  #detalle_tiempos_equipos.Segundo_Inicio ASC
...
Si encuentras algún error en el código o si se puede hacer más simple pues estaré atento. Muchas gracias :D
Tu solución es valida pero no es optima, ¿qué pasa si tienes que pasar más de 3 códigos en la variable?
Te recomiendo lo que te puse en el hilo anterior, tu solución seria así:
Declare @sql nvarchar(max)
set @sql= 'SELECT
  hist_statusevents.eqmt AS Equipo,
    hist_statusevents.shiftindex AS Turno,
    hist_statusevents.starttime AS Segundo_Inicio,
  hist_statusevents.endtime As Segundo_Termino,
    hist_statusevents.category AS Categoria
INTO
    #detalle_tiempos_equipos
FROM
    hist_statusevents
WHERE
    (hist_statusevents.shiftindex BETWEEN @STARTD AND @ENDD) AND
    (hist_statusevents.eqmt IN'+ @FLOTAS+ ')
ORDER BY
  #detalle_tiempos_equipos.Equipo,
  #detalle_tiempos_equipos.Turno,
  #detalle_tiempos_equipos.Segundo_Inicio ASC'
Exec (@SQL)
Hola Brownsea, muchas gracias por tu respuesta! Me ahorra el procesar la cadena de caracteres lo cual es muy bueno, solo tuve que hacer un par de cambios al setear @SQL, puesto que @STARTD Y @ENDD eran variables int y no me reconocía el objeto #detalles_tiempos_equipos dentro de la cadena @SQL y finalmente quedó así:
DECLARE @STARTD as int
DECLARE @ENDD as int
DECLARE @FLOTAS as varchar(1000)
DECLARE @SQL as varchar(1000)
SET @STARTD = 28368
SET @ENDD = 28427
SET @FLOTAS = '(''CAM332'',''CAM333'',''CAM334'')'
CREATE TABLE #detalle_tiempos_equipos (Equipo varchar(10),Turno int, Segundo_Inicio int, Segundo_Termino int, Categoria int)
SET @SQL = 'SELECT
    hist_statusevents.eqmt AS Equipo,
    hist_statusevents.shiftindex AS Turno,
    hist_statusevents.starttime AS Segundo_Inicio,
    hist_statusevents.endtime As Segundo_Termino,
    hist_statusevents.category AS Categoria
  FROM
    hist_statusevents
  WHERE
    (hist_statusevents.shiftindex BETWEEN '+ CAST(@STARTD as varchar(10)) +' AND '+ CAST(@ENDD as varchar(10)) +') AND
    (hist_statusevents.eqmt IN '+ @FLOTAS +')
  ORDER BY
    #detalle_tiempos_equipos.Equipo,
    #detalle_tiempos_equipos.Turno,
    #detalle_tiempos_equipos.Segundo_Inicio ASC'
INSERT INTO #detalle_tiempos_equipos exec (@SQL)
...
Con eso me ahorro mucho trabajo ya que no necesito procesar la cadena y no necesito tratar de entender lo que hace ese proceso (si otra persona quisiera leer ese código podría ser muy engorroso). Muchas gracias y que tengas un buen día! :D
Por nada, no te olvides cerrar la pregunta.
Muchas gracias por tomarte el tiempo para analizar y responder mi pregunta, si todos compartieran su conocimiento y fueran así de amables como son en esta comunidad, este mundo sería mucho más sencillo. Saludos! :D
Respuesta

brownsea en este caso quiero insertar una consulta en una cadena, el resultado me vota los items en varias filas, como podría hacer para que me resulta en una sola fila, gracias de antemano!

DECLARE @CADENA VARCHAR(1000)
SET @CADENA = 'select cod_item as item from #TABLA where dif <= 0'
Exec (@CADENA)

Resultado

item

AX000147
AX000079

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas