2

I have a stored procedure to generate a text file, which one has a lot of filters, here it is

-- =============================================
-- Author:      Ricardo Ríos
-- Create date: 17/01/2014
-- Description: Genera el TXT para Importar a Saint
-- =============================================
ALTER PROCEDURE [dbo].[SP_SAINT_TXT]
    -- Add the parameters for the stored procedure here
        (   
        @nomina VARCHAR(MAX),
        @gerencia VARCHAR(MAX),
        @sucursal VARCHAR(MAX),
        @empresa VARCHAR(MAX),
        @departamento VARCHAR(MAX),
        @cargo VARCHAR(MAX),
        @horario VARCHAR(MAX),
        @locacion VARCHAR(MAX),
        @empleados VARCHAR(MAX),
        @desde DATETIME,
        @hasta DATETIME
        )
AS
BEGIN

SET NOCOUNT ON;

DECLARE @cedula varchar(max), @exnocturnas DECIMAL(5,2),
@diast DECIMAL(5,2), @diasf DECIMAL(5,0), @diasd DECIMAL(5,2),
@matut DECIMAL(5,2), @vespe DECIMAL(5,2), @noctu DECIMAL(5,2),
@linea varchar(max), @txt varchar(max),  
@l1 varchar(max),
@l2 varchar(max),
@l3 varchar(max),
@l4 varchar(max),
@l5 varchar(max),
@l6 varchar(max),
@l7 varchar(max)
SET @txt = ''

SET @nomina = (SELECT REPLACE(@nomina, '(', ''))
SET @nomina = (SELECT REPLACE(@nomina, ')', ''))
SET @gerencia = (SELECT REPLACE(@gerencia, '(', ''))
SET @gerencia = (SELECT REPLACE(@gerencia, ')', ''))
SET @sucursal = (SELECT REPLACE(@sucursal, '(', ''))
SET @sucursal = (SELECT REPLACE(@sucursal, ')', ''))
SET @empresa = (SELECT REPLACE(@empresa, '(', ''))
SET @empresa = (SELECT REPLACE(@empresa, ')', ''))
SET @departamento = (SELECT REPLACE(@departamento, '(', ''))
SET @departamento = (SELECT REPLACE(@departamento, ')', ''))
SET @cargo = (SELECT REPLACE(@cargo, '(', ''))
SET @cargo = (SELECT REPLACE(@cargo, ')', ''))
SET @locacion = (SELECT REPLACE(@locacion,'(',''))
SET @locacion = (SELECT REPLACE(@locacion,')',''))
SET @empleados = (SELECT REPLACE(@empleados,'(',''))
SET @empleados = (SELECT REPLACE(@empleados,')',''))

    declare cursor_txt cursor for
    SELECT B.ID AS cedula, 
    SUM(A.extrasnocturnas) AS extrasnocturnas, 
    SUM(A.diastrabajados) AS diastrabajados, 
    SUM(A.diasfaltantes) AS diasfaltantes, 
    SUM(A.diasdescanso) AS diasdescanso, 
    SUM(A.maturinas) AS maturinas, 
    SUM(A.vespertinas) AS vespertinas, 
    SUM(A.nocturnas) AS nocturnas
    FROM exsaint A
    RIGHT JOIN tabela B ON A.cedula = B.ID
    WHERE A.desde >= @desde AND A.hasta <= @hasta
    AND B.tipo_nomina IN (CASE WHEN @nomina = '-1' THEN B.tipo_nomina ELSE @nomina END)
    AND B.gerencia IN (CASE WHEN @gerencia = '-1' THEN B.gerencia ELSE @gerencia END)
    AND B.sucursal IN (CASE WHEN @sucursal = '-1' THEN B.sucursal ELSE @sucursal END)
    AND B.empresa IN (CASE WHEN @empresa = '-1' THEN B.empresa ELSE @empresa END)
    AND B.departamento IN (CASE WHEN @departamento = '-1' THEN B.departamento ELSE @departamento END)
    AND B.cargo IN (CASE WHEN @cargo = '-1' THEN B.cargo ELSE @cargo END)
    AND B.locacion IN (CASE WHEN @locacion = '-1' THEN B.locacion ELSE @locacion END)
    AND B.ID IN (CASE WHEN @empleados = '-1'THEN B.ID ELSE @empleados END)
    GROUP BY ID
    ORDER BY ID
    open cursor_txt
        fetch next from cursor_txt into @cedula, @exnocturnas, @diast, @diasf, @diasd, @matut, @vespe, @noctu

        while @@fetch_status = 0
        begin
            SET @linea = ''
            SET @l1 = CAST(@exnocturnas AS CHAR(8))
            SET @l2 = CAST(@diast AS CHAR(8))
            SET @l3 = CAST(@diasf AS CHAR(3))
            SET @l4 = CAST(@diasd AS CHAR(8))
            SET @l5 = CAST(@matut AS CHAR(8))
            SET @l6 = CAST(@vespe AS CHAR(8))
            SET @l7 = CAST(@noctu AS CHAR(8))
            SET @linea = 
                LTRIM(CONVERT(CHAR(16),@cedula)) +  
                LTRIM(RTRIM((SELECT CONVERT(VARCHAR(10), @hasta, 103) AS [DD/MM/YYYY]))) + 
                LTRIM(RTRIM('000')) + 
                LTRIM(RTRIM(REPLICATE('0', 8-LEN(@l1)) + @l1 )) +
                LTRIM(RTRIM(REPLICATE('0', 8-LEN(@l2)) + @l2 )) +
                LTRIM(RTRIM(REPLICATE('0', 3-LEN(@l3)) + @l3 )) + 
                LTRIM(RTRIM(REPLICATE('0', 8-LEN(@l4)) + @l4 )) +
                LTRIM(RTRIM(REPLICATE('0', 8-LEN(@l5)) + @l5 )) +
                LTRIM(RTRIM(REPLICATE('0', 8-LEN(@l6)) + @l6 )) +
                LTRIM(RTRIM(REPLICATE('0', 8-LEN(@l7)) + @l7 )) +
                LTRIM(RTRIM('00000000')) +
                + CHAR(13) + CHAR(10);
            PRINT @txt
            PRINT @linea
            SET @txt = @txt + @linea
            fetch next from cursor_txt into @cedula, @exnocturnas, @diast, @diasf, @diasd, @matut, @vespe, @noctu
        end
    close cursor_txt
    deallocate cursor_txt

    SELECT @txt

END

The issue is when I pass some values to the IN filter I get this error.

[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting the varchar value ' 5 , 4 ' to data type int.

When I execute the stored procedure like below.

EXECUTE SP_SAINT_TXT '-1', '-1', '-1', '( 5 , 4 )', '-1', '-1', '-1', '-1', '-1', '20140801', '20150802'   

Is there a way that I can add those filters with some conversions or something else and it works?

4

3 Answers 3

6
+50

CASE inside IN statements for this task seems not possible because CASE only capable of returning scalar value, according to this post. Also, SQL Server can't naturally deal with comma-separated value. If you can afford to change the parameter to a more appropriate data type like table parameter, that would be the ultimate solution.

Otherwise, there are some possible workaround that you can attempt to implement for this task here. This one based on the answer by @CeejeeB. Change this part of your SQL.. :

AND B.empresa IN (CASE WHEN @empresa = '-1' THEN B.empresa ELSE @empresa END)

..to this :

AND (
     @empresa = '-1' 
        or 
     B.empresa IN (SELECT t.id.value('.', 'int') id FROM @empresaXml.nodes('//s') as t(id))
    )

The above statement always evaluates to True when @empresa = '-1'. Otherwise, int values will be extracted from @empresaXml variable and will be used to filter column empresa.

The variable @empresaXml it self declared and populated as follow :

DECLARE @empresaXml XML
SET @empresaXml = CAST('<s>' + REPLACE(@empresa, ',', '</s><s>') + '</s>' AS XML)

SQL Fiddle Demo :

CREATE TABLE MyTable(empresa int, data varchar(10))
;

INSERT INTO MyTable
VALUES
  (1,'a'),
  (2,'b'),
  (3,'c'),
  (4,'d'),
  (5,'e')
;

Declare @empresa varchar(50) = '( 5 , 4 )'
DECLARE @empresaXml XML

SET @empresa = REPLACE(REPLACE(@empresa,'(',''), ')', '')
SET @empresaXml = CAST('<s>' + REPLACE(@empresa, ',', '</s><s>') + '</s>' AS XML)

SELECT *
FROM MyTable B
WHERE (@empresa = '-1' or B.empresa IN (SELECT t.id.value('.', 'int') id
                          FROM @empresaXml.nodes('//s') as t(id)))

output :

| empresa | data |
|---------|------|
|       4 |    d |
|       5 |    e |
6
  • 1
    Add a recommendation to use OPTION(RECOMPILE) as discussed in Dynamic Search Conditions in T‑SQL and you'll have my upvote. Aug 5, 2015 at 11:14
  • I get this strange error now -> Msg 1934, Level 16, State 1, Procedure SP_SAINT_TXT, Line 64 SELECT failed because the following SET options have incorrect settings: 'NUMERIC_ROUNDABORT'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations. Aug 5, 2015 at 23:53
  • @RicardoRios what is in line 64, SELECT B.ID AS cedula, ? Try without OPTION(RECOMPILE) first (If you were using it). What value you used for testing, '( 5 , 4 )'?
    – har07
    Aug 6, 2015 at 1:41
  • I am testing with this -> EXECUTE SP_SAINT_TXT '( 4 , 1 , 2 , 3 , 6 )','-1','-1','( 5 , 6 , 1 , 4 , 3 , 2 )','-1','-1','-1','-1','-1','20140801','20150805' and it looks like line 64 is this one SET @XMLlocacion = CAST('<s>' + REPLACE(@locacion, ',', '</s><s>') + '</s>' AS XML) Aug 6, 2015 at 1:49
  • @RicardoRios I can't reproduce the problem with that parameter. The error message says Line 64 SELECT failed..., it is strange if you find that Line 64 doesn't have any SELECT there. Anyway, it is hard to diagnose if I can't reproduce the error
    – har07
    Aug 6, 2015 at 1:59
1

Ah, the issue is that its treating it like a varchar, not an integer.

What you need to do is split them out, either into another table or XML. Best explained here:

Passing a varchar full of comma delimited values to a SQL Server IN function

EDIT: Link only answers are bad, so here is the method I use (from that link):

Declare @Ids varchar(50)
Set @Ids = ‘1,2,3,5,4,6,7,98,234’

DECLARE @XML XML
SET @XML = CAST('<i>' + REPLACE(@Ids, ',', '</i><i>') + '</i>' AS XML)

SELECT * 
FROM
    SomeTable 
INNER JOIN @XML.nodes('i') x(i) 
    ON  SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')
1
  • I think this is not the best way to fix these, because I have several filters, also tried the link provided, still no success Aug 2, 2015 at 21:32
1

I was able to complete this using a Split function.

I use this DelimitedSplit8k function that Jeff Moden posted on SQLServerCentral in 2012 here: http://www.sqlservercentral.com/articles/Tally+Table/72993/

You can add the Function to your database (3rd to last code box in the article) and then call it like this:

 AND B.empresa IN (CASE WHEN @empresa = '-1' THEN B.empresa ELSE (SELECT split.item from DelimitedSplit8k(@empresa,',') split) END)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.